Wordpress:如何获取标头图像ID

时间:2016-06-13 15:41:39

标签: php wordpress

短篇小说: 我试图在Wordpress中获取标题图像的ID。

我发现的只是这本指南,它似乎不再适用了:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/

长篇故事 我尝试使用srcset使WP Header响应。所以我不想使用这段代码

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

...而是想使用wp_get_attachment_image_srcset函数来获取我的标题图像的srcset。唯一的问题:我需要这个功能的图像ID - &gt;我的标题图片的ID。

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

有什么建议吗?

3 个答案:

答案 0 :(得分: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等内容,以允许响应图像。

答案 1 :(得分:0)

为了回答原来的问题,我在过滤由<?php the_header_image_tag(); ?>输出的标记(在v4.4中引入)时,找到了获取ID的最简单方法。

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

答案 2 :(得分:0)

具有备用广告的响应式Wordpress标头图片:

if (get_header_image() !== '') {
    $attachment_id = attachment_url_to_postid(get_header_image());
    echo wp_get_attachment_image($attachment_id, 'large');
} 
if (get_header_image() == '') {
    echo '<h1>'.get_bloginfo( "name" ).'</h1>';
    echo '<h2>'.get_bloginfo( "description" ).'</h2>';
}