从WordPress中的帖子中获取所有图库图像/附件


Get all gallery images / attachments from a post in WordPress

我需要什么:

  1. 用户通过WordPress Media Uploader将图片上传到图库中,并在帖子中发布。假设post_id = 1,帖子是: [gallery ids"1,2,3,...,n"]
  2. 我需要一个函数来获取此库中post_id = 1的所有图像 ID。
  3. 图像应该喜欢".../post-title/attachment/image-title"

我试过:

$attachements = query_posts(
    array(
        'post_type' => 'attachment',  
        'post_parent' => $post->ID,   
        'posts_per_page' => -1        
         )
);
var_dump($attachements);

我的输出是:

array(0) { }

我是不是太傻了?

get_post_galleries()可用于

获取有关帖子中每个图库的信息。 确保在$post_id后传递false以仅返回数据。

从那时起,您可以遍历不同的库并从ids键中提取ids。这实际上是一个字符串,因此您需要将其explode()到一个数组中,该数组将与array_merge()一起使用以添加到ids的总列表中。

由于可以包含重复的ids,运行array_unique()将确保每个id只列出一次。

$post_id = 298;
$image_ids = array ();
// get all the galleries in the post
if ( $galleries = get_post_galleries( $post_id, false ) ) {
    foreach ( $galleries as $gallery ) {
        // pull the ids from each gallery
        if ( ! empty ( $gallery[ 'ids' ] ) ) {
            // merge into our final list
            $image_ids = array_merge( $image_ids, explode( ',', $gallery[ 'ids' ] ) );
        }
    }
}
// make the values unique
$image_ids = array_unique( $image_ids );    
// convert the ids to urls -- $gallery[ 'src' ] already holds this info
$image_urls = array_map( "wp_get_attachment_url", $image_ids );    
// ---------------------------- //
echo '<pre>';
print_r ( $image_ids );
print_r ( $image_urls );
echo '</pre>';

尝试以下代码

 $args = array( 
'post_type' => 'attachment', 
'numberposts' => -1, 
'post_status' => null, 
'post_parent' => $page->ID);
$attachments = get_posts( $args );
var_dump($attachements);

你试过get_post_galleries吗?

http://codex.wordpress.org/Function_Reference/get_post_galleries