【问题标题】:Get all gallery images / attachments from a post in WordPress从 WordPress 中的帖子中获取所有图库图像/附件
【发布时间】:2013-09-21 14:31:43
【问题描述】:

我需要什么:

  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) { }

我是不是太傻了?

【问题讨论】:

    标签: php wordpress post gallery attachment


    【解决方案1】:

    试试下面的代码

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

    【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      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>';
      

      【讨论】:

        猜你喜欢
        • 2015-05-10
        • 2013-10-09
        • 2016-05-04
        • 1970-01-01
        • 2013-07-27
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多