Depending on the type of design for a site, there are several reasons why you would want to use the featured image of a post/page as the background image for either the body, or a specific element.
For any post/page, WordPress seamlessly allows to call the featured image (or the post image as some would recognize it) and use it as necessary. The snippet below starts by calling the queried object, then gets the post thumbnail for the called object, and then creates and assigns the URL for the featured image.
The CSS inside the <style> should be changed according to the needs, and use ws_post_bg to get the URL for the image.
<?php function ws_post_bg() { if(is_single()) { $ws_post_id = get_queried_object_id(); $ws_post_thumb_id = get_post_thumbnail_id( $ws_post_id ); $ws_post_bg = wp_get_attachment_url( $ws_post_thumb_id ); ?> <style> #element { background-image: url(<? echo $ws_post_bg ?>); background-position: center center; } </style> <? } } add_action('wp_head', 'ws_post_bg');
The code above will add the featured image as the background image to all the posts. That is defined by the is_single
conditional tag.
How To Use Featured Image Background on a Single Page/Post?
The snippet above uses the is_single
conditional tag, and just like that it can use any conditional tag accepted by WordPress.
For a particular page or post, you’ll be using a tag that looks similar to is_page(42)
or is_single(12)
whereby the 42 and 12 are the IDs of the page and post respectively.
Feel free to change it depending on what you need to use it for – all the conditional tags accepted by WordPress will work flawlessly.