2016-06-13 39 views
1

短故事: 我試圖在Wordpress中獲取標題圖像的ID。WordPress的:如何獲得標題圖片ID

所有我發現了這個指南,不到風度似乎不再起作用:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/

長篇 我試圖讓WP頭響應與srcset。所以我不想使用此代碼

<img id="masthead-bg" src="<?php header_image() ?>" alt=""> 

...而是想用wp_get_attachment_image_srcset功能讓我的頭圖像的srcset。唯一的問題:我需要此功能的圖像ID - >我的標題圖像的ID。

<img id="masthead-bg" 
src="<?php header_image() ?>" 
srcset="<?php echo wp_get_attachment_image_srcset(image_id(), 'thumbnail'); ?>" 
sizes="100vw" alt=""> 

有什麼建議嗎?

回答

1

嘗試......

// Get the header image data  
    $data = get_object_vars(get_theme_mod('header_image_data')); 

    // Now check to see if there is an id  
    $attachment_id = is_array($data) && isset($data['attachment_id']) ? $data['attachment_id'] : false; 

    if($attachment_id) { 
     // Put your image code here, user whatever function to get image by id you need 
    } 

注:如果您使用合適的WordPress的函數來獲取圖像,應該添加在你的所有srcset等東西,以允許響應圖像。

+0

嗨西蒙!這似乎是我上面鏈接的代碼......這對我沒有用,因爲它沒有返回任何值。即使設置了自定義標題圖像,'$ attachment_id'也是空的......不知道爲什麼。 獲得標題圖片的Wordpress函數是'<?php header_image()?>',它只給我一個URL。或者我錯過了顯示自定義標頭的功能? 似乎WP忘了讓那些響應.... –

+0

嗯,這是非常奇怪的,如果沒有返回任何東西。 $ data是否包含任何內容或者是否爲null。完全同意,如果header_image()沒有返回一個有點奇怪的響應圖像。 –

+0

瘋狂..當我只顯示整個'$ data'數組時,它顯示我'attachment_id = 245'(或任何我設置的標題圖像)。所以$ data數組有正確的信息......但第二行代碼似乎弄亂了某些東西。 –

0

要回答最初的問題,我找到了最簡單的方法來獲取ID,同時過濾由<?php the_header_image_tag(); ?>(在v4.4中引入)輸出的標記。

function header_img_markup($html, $header, $attr) { 

    // we can get the image ID by passing its src url to this method 
    $header_img_id = attachment_url_to_postid($attr['src']); 

    // now we can get its metadata from the db 
    $header_img_data = wp_get_attachment_metadata($header_img_id); 

    // now we can use the data 
    $customSizeWidth = $header_img_data['sizes']['my-custom-size']['width']; 

    // ...your custom output here... 
    return $html; 
} 
add_filter('get_header_image_tag', 'header_img_markup', 20, 3); 
相關問題