2016-12-30 141 views
1

我在這裏使用此代碼來使用自定義分類從媒體庫中獲取圖像。它獲得的圖像網址很好,但我想獲得圖像ID和標題。我怎麼做? 這是我到目前爲止。WordPress的媒體庫自定義分類獲取圖像

function get_images_from_media_library($cat) { 
    $args = array(
     'post_type' => 'attachment', 
     'post_mime_type' =>'image', 
     'post_status' => 'inherit', 
     'posts_per_page' => 6, 
     'orderby' => 'rand', 
     'tax_query' => array(
      array(
      'taxonomy' => 'gallery-category', 
      'field' => 'slug', 
      'terms' => $cat 
      ) 
     ) 
     ); 
    $query_images = new WP_Query($args); 
    $images = array(); 
    foreach ($query_images->posts as $image) { 
    $images[]= $image->guid; 
    echo $image->ID; // Returns image ID, but I need it in display_images_from_media_library function 
    } 
    return $images; 
} 
function display_images_from_media_library($cat) { 
    $imgs = get_images_from_media_library($cat); 
    foreach($imgs as $img) { 
    $html .= '<img src="' . $img . '" alt="">'; 
    } 
    return $html; 
} 

回答

1

get_images_from_media_library()返回圖像的URL的陣列因此display_images_from_media_library()從未訪問比這些網址其它任何東西。如果你想訪問ID和標題,你需要做幾個更新。

內部get_images_from_media_library(),改變該:

$images = array(); 
foreach ($query_images->posts as $image) { 
    $images[]= $image->guid; 
    echo $image->ID; // Returns image ID, but I need it in display_images_from_media_library function 
} 
return $images; 

向該:

return $query_images->posts; 

原代碼的影像環並加入它們的URL到一個新的數組。這裏我們將以原始形式返回圖像。

然後,我們需要更新使用這些圖像的功能。

更改此:

$html .= '<img src="' . $img . '" alt="">'; 

要這樣:

$html .= '<img src="' . $img->guid . '" alt="">'; 

在我的答案我已經修改了你寫在希望的結果得出的代碼。不過,我會建議你首先改變你檢索圖像的方式。 WP_Query不是處理它的最有效方式。改爲考慮get_posts()

相關問題