2013-04-17 50 views
0

我想獲得我的類別3的所有圖像附件ID。 有人知道該怎麼做嗎?從類別中獲取所有圖像url - Wordpress

這裏是我的代碼:

$query_images_args = array(
     'post_type' => 'attachment', 
     'post_mime_type' =>'image', 
     'post_status' => 'inherit', 
     'posts_per_page' => -1,  
//  'cat'=> 3, NOT WORKING 
     'orderby' => 'rand', // Order randomly 
    ); 

    $query_images = new WP_Query($query_images_args); 
    $images_desktop = array(); 
    $images_tablets = array(); 
    $images_smartphones = array(); 


    // WE ARE GETTING ALL IMAGES URLS ACCORDING TO THE DEVICE 
    foreach ($query_images->posts as $image) { 

    $attachment_width = wp_get_attachment_image_src($image->ID,'small'); 
    $attachment_width = $attachment_width[1]; 
     if($attachment_width<=500) 
     { 
      $images_smartphones[] = wp_get_attachment_url($image->ID); 
     } 
     elseif ($attachment_width<=1000) 
     { 
      $images_tablets[] = wp_get_attachment_url($image->ID); 
     } 
     elseif ($attachment_width>=1000){ 
      $images_desktop[]= wp_get_attachment_url($image->ID); 
     } 
    } 
    ?> 

我的想法:

獲得第3類的所有帖子ID,如果他們有任何圖像附件。 通過這個帖子ID列表,我可以獲得每個附件ID的列表。 這是正確的嗎?

感謝

+0

您需要首先獲取在類別,然後將獲得基於已檢索HTTP職務圖像的帖子://wordpress.stackexchange .COM /問題/ 56562 /如何對運行WP-查詢 - 回收 - 附件到帖子,只從 - A-特定-美食 –

回答

1

這是我工作的代碼

<?php wp_reset_query(); 

// Init 
    $images_desktop = array(); 
    $images_tablets = array(); 
    $images_smartphones = array(); 

    $args = array( 
     'orderby' => 'rand', 
     'post_type' => 'post', 
     'cat' => 3, 
     'posts_per_page' => -1, 
    ); 

    $wp_query = new WP_Query($args);     
// $wp_query->posts returns all posts even childrens 

    foreach ($wp_query->posts as $single_post) { 
     $single_post_ID = $single_post->ID; 
//  echo ($single_post_ID."<br/>"); 
     $args = array(
      'orderby' => 'rand', // Order randomly 
      'post_type'  => 'attachment', 
      'post_parent' => $single_post_ID, 
      'post_mime_type' => 'image', 
      'post_status' => null, 
      'numberposts' => -1, 
     ); 

     $attachments = get_posts($args); 
     if ($attachments) { 
      foreach ($attachments as $attachment) { 
       $attachment_ID = $attachment->ID; 

       $attachment_width = wp_get_attachment_metadata($attachment_ID); 
       $attachment_width = $attachment_width["width"]; 
       if($attachment_width<=500) 
       { 
        $images_smartphones[] = wp_get_attachment_url($attachment_ID); 
       } 
       elseif ($attachment_width<=1000) 
       { 
        $images_tablets[] = wp_get_attachment_url($attachment_ID); 
       } 
       elseif ($attachment_width>=1000){ 
        $images_desktop[]= wp_get_attachment_url($attachment_ID); 
       } 

      } 
     } 
    } 

    ?> 
相關問題