我想做什么
我有一个网站使用我前段时间写的CMS,现在我正在尝试将其迁移到wordpress。
在现有的实现中,当有人写帖子时,他们可以添加一些额外的图像,这些图像在帖子末尾显示为图库,例如,如您在此页面中看到的那样(抱歉非英语页面):http://apollonpatras.gr/news/562/i-bradia-ton-xorigon-parousiasi-xorigikou-programmatos-kai-eisitirion-diarkeias/。
我认为我能怎么做
我正在考虑让用户创建wordpress画廊,并在保存帖子时拦截帖子内容并将图库图像ID存储在postmeta字段中,以便我可以随心所欲地显示它们。
此外,在显示画廊之前,我必须从内容中删除它们,因为我稍后会以自己的方式显示它们。
到目前为止我正在尝试什么
add_filter('content_save_pre', 'intercept_galleries', 99);
function intercept_galleries($content) {
if (get_post_type() !== 'post') {
return $content;
}
if (has_shortcode($content, 'gallery')) {
// The [gallery] short code exists.
$a = get_post_gallery(0, false);
update_post_meta(get_the_ID(), 'has_gallery', 1);
update_post_meta(get_the_ID(), 'gallery_items', $a['ids']);
} else {
update_post_meta(get_the_ID(), 'has_gallery', 0);
update_post_meta(get_the_ID(), 'gallery_items', "");
}
return $content;
}
add_filter('the_content', 'remove_shortcodes_from_content');
function remove_shortcodes_from_content($content) {
return strip_shortcodes($content);
}
哪里出错了
看起来最初保存帖子时,postmeta 字段"has_gallery"设置为 1,但字段"gallery_items"为空。
当我转到wordpress编辑器并点击更新时,字段是绝对正确的。
此外,从内容中删除短代码的钩子也在工作。
我在寻找什么
如何解决此问题?另外,我决定这样做的方式有什么错误/愚蠢的地方吗?其他方式会更清洁/更容易/更快等吗?
谢谢你的时间
我已经这样做了几次,这是我的做法。
首先,我创建一个函数,该函数将以我想要的方式显示库。 您可以根据对库标记的要求对其进行修改:
function my_gallery_shortcode( $attr ) {
$post = get_post();
if ( ! empty( $attr['ids'] ) ) {
$attr['include'] = $attr['ids'];
}
extract( shortcode_atts( array(
'order' => 'ASC',
'orderby' => 'post__in',
'id' => $post->ID,
'columns' => 3,
'size' => 'large',
'include' => '',
), $attr));
$id = (int) $id;
$columns = (int) $columns;
if ( 'RAND' == $order ) {
$orderby = 'none';
}
if ( ! empty( $include ) ) {
$_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if ( empty( $attachments ) ) {
return '';
}
$output = '<div class="slideshow"><ul>';
foreach ( $attachments as $id => $attachment ) {
$thumb = wp_get_attachment_image_src( $id, 'large', false );
$output .= '<li><img src="' . $thumb[0] . '" width="' . $thumb[1] . '" height="' . $thumb[2] . '" alt="' . get_post_meta( $id, '_wp_attachment_image_alt', true ) . '" /></li>';
}
$output .= '</ul></div>';
return $output;
}
您可以根据需要复杂化或简单地使用上述功能。
然后在主题的functions.php
中添加以下内容:
add_shortcode( 'gallery', 'my_gallery_shortcode' );
现在您有两个选择:
1) 您可以允许用户通过编辑相关页面并转到Media > Create Gallery
这将插入图库短代码,该代码将根据您的函数my_gallery_shortcode()
进行格式化,但是图库可以通过管理区域中的WordPress图库功能进行管理,并由WordPress以常规方式存储在数据库中。
或
2) 您可以通过functions.php
文件中的其他代码或使用高级自定义字段等插件创建单独的所见即所得字段。 然后,您将使用此附加的 WYSIWYG 字段允许用户以与上述相同的方式插入库短代码。 这实际上与上面的选项 1 相同,但您可以更灵活地输出和定位库在页面上的位置。
我希望这能帮助任何想要做同样事情的人。