Usually, when you set the background image thru the WordPress customizer, it’s for the whole site. If you want to set a different image background on each page, you have to dive into the code.
There are two ways to do it. First and easiest way, you can…
Use the featured image
Just add the following lines in the functions.php
file of your child theme:
function tsct_addPageBackground() { if ( is_page() ): $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'twentyseventeen-featured-image' ); if ( !empty( $thumbnail ) ): $bgImage = '.site-content {background-image: url('.$thumbnail.') !important;}'; wp_add_inline_style( 'twentyseventeen-style', $bgImage ); endif; endif; } add_action( 'wp_enqueue_scripts', 'tsct_addPageBackground', 11 );
And, of course, don’t forget to set your featured image!
But you may want to have both featured image and background image for a page.
In such a case, you have to…
Use Custom Fields
For the classic editor, the custom fields are below the editing window, but they are not displayed by default; you will have to click on Screen options (top right in the browser) then check Custom fields.
You wont find custom fields using Gutenberg Editor. But don’t worry, the feature is just deactivated.
There are three vertical dots at the top of the editor on the right. Click, scroll down to Options, then check Custom fields. You will have to click on Save and reload and tada! it works!
Add a custom field, name it, bgimg
for example.
Enter the image url (or copy / paste from the media library). In the functions.php
file of your child theme, add the following lines:
function tsct_addPageBackground() { if ( is_page() ): $custom_fields = get_post_custom(); $my_custom_field = $custom_fields['bgimg']; if ( !empty( $my_custom_field ) ): $bgImage = '.site-content {background-image: url('.$custom_fields['bgimg'][0].') !important;}'; wp_add_inline_style( 'twentyseventeen-style', $bgImage ); endif; endif; } add_action( 'wp_enqueue_scripts', 'tsct_addPageBackground', 11 );
You can also put those code snippets in a special container thru Code Snippets plugin if you don’t need a child theme. Check Only run on site front-end, save it and activate it.
That’s all folks!