我刚刚更新到Wordpress 3.5,但这破坏了我的代码的一小部分: 有一个php文件,它通过AJAX加载一个特定的帖子及其库。
代码如下:
<?php
// Include WordPress
define('WP_USE_THEMES', false);
require('../../../../wp-load.php');
$id = $_POST['id'];
// query post with this identifier
query_posts('meta_key=identifier&meta_value='.$id);
if (have_posts()) :
while (have_posts()) : the_post();
// add content
$content = apply_filters('the_content', get_the_content());
echo '<div class="content-inner">'.$content.'</div>';
endwhile;
endif;
?>
该帖子包含[gallery]短代码。我用这段代码构建了自己的Wordpress库:
remove_shortcode('gallery');
add_shortcode('gallery', 'parse_gallery_shortcode');
function parse_gallery_shortcode($atts) {
global $post;
extract(shortcode_atts(array(
'orderby' => 'menu_order ASC, ID ASC',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'full',
'link' => 'file'
), $atts));
$args = array(
'post_type' => 'attachment',
'post_parent' => $id,
'numberposts' => -1,
'orderby' => $orderby
);
$images = get_posts($args);
print_r($images);
}
这适用于我网站上的所有其他图库,但不适用于加载了ajax的图库。它与Wordpress 3.4一起使用。
我忽略了Wordpress 3.5的变化吗?
答案 0 :(得分:2)
我明白了:如果您使用带有已上传到媒体库的图片的图库,则图库短代码看起来像[gallery ids=1,2,3]
,这意味着图片仅链接(并且未附加)到画廊,所以post_type=attachment
不起作用。
现在我正在使用正则表达式来获取图像ID:
$post_content = $post->post_content;
preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
$array_id = explode(",", $ids[1]);
答案 1 :(得分:1)
现在可以使用$post->ID
和galleries提取所有gallery甚至一个get_post_galleries()
。每个图库都会包含ids
中的图片ID列表以及src
中的image urls列表。 gallery对象基本上是短代码参数,因此您也可以访问它们。
if ( $galleries = get_post_galleries( $post->ID, false ) ) {
$defaults = array (
'orderby' => 'menu_order ASC, ID ASC',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'full',
'link' => 'file',
'ids' => "",
'src' => array (),
);
foreach ( $galleries as $gallery ) {
// defaults
$args = wp_parse_args( $gallery, $defaults );
// image ids
$args[ 'ids' ] = explode( ',', $args[ 'ids' ] );
// image urls
$images = $args[ 'src' ];
}
}