I’m looking for a way to get the ID of the background_image when I am using custom headers?

I tired using url_to_postid like this:

$url = get_header_image()
$postid = url_to_postid( $url );

and
$url = get_theme_mod(‘header-image’)
$postid = url_to_postid( $url );

I got a null value for both, which I realized is because both get_header_image() and get_theme_mod('header-image') return the url in the form of example.com/wp-content/uploads… but what url_to_postid needs is example.com/?attachment_id=#.

I also thought about get_theme_mods(); but it only returns the long url for background image. Not the shorter url or the ID. It does give the id for the header image though, grrr.

What am I missing here?

For the record I’m doing this so I can get the background image with wp_get_attachment_image_src() in a dynamic stylesheet and use the $size arg, with some custom sizes to return a different size depending on the screen size. That way I can do full screen backgrounds without having to load and scale down some massive image for a phone’s screen. Alternative solutions to my actual problem are more than welcome.

1 Answer
1

Query for post meta keys _wp_attachment_is_custom_background or _wp_attachment_is_custom_background:

function t5_bg_img_id()
{
    if ( ! $bg_img = get_background_image() )
        return FALSE;

    $query = array(
        'post_type'  => 'attachment',
        'fields'     => 'ids',
        'meta_query' => array (
            array (
                'key' => '_wp_attachment_is_custom_background',
                'value'   => get_option( 'stylesheet' ),
                'compare' => '==',
            ),
            array (
                'key' => '_wp_attachment_metadata',
                'value'   => basename( $bg_img ),
                'compare' => 'LIKE',
            )
        )
    );

    if ( array () === $bg_post = get_posts( $query ) )
        return FALSE;

    return $bg_post[0];
}

Leave a Reply

Your email address will not be published. Required fields are marked *