How to get attachment id of background image?

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 Comment