This tutorial provides the solution which enables you to change the background image on posts based on which category the post is assigned to.
Based on the following question from a member of the genesis community :
How can I change the background on a post based on the category of the post? I.E. – I have a series of post topics in Category 1, another series of post topics in Category 2. All posts in Category 1 are to have Cat1.jpg for the background, all topics in Category 2 are to have Cat2.jpg for the background.
Shows how the same background image once added to the edit category screen can be displayed on all posts in the same category as well as the category page itself. Also shows how a default image can be set to display on single posts in the same category when one hasn’t been added yet to the category edit screen. And also shows how the image added to the customizer is used as the background on all other pages.
Here’s the code snippets which provide 2 different solutions :
Solution 1 – Pure PHP Code
Copy & paste the PHP code from the file named solution-1.php to the end of your child themes functions.php file and swap out the category ID’s to match what’s generated by your installation.
The code filters the function which adds the background image using the WordPress customizer enabling you to add different images conditionally.
you can then dd your images to your child themes images folder.
Solution 2 – Uses ACF & PHP Code
The ACF plugin enables you to upload a unique image via the category archive edit screen.
# Step 1 – You can then use the PHP code from the file named solution-1.php in your child themes functions file to filter the function which adds the background image ( via the WordPress customizer ) enabling you to add different images conditionally.
The code enables you to display the image you add to the category edit screen as the background on single posts in that category as well as the category page itself. If no image is added to the category edit screen, a default image is used in its place which is pulled from your child themes images folder. In this case it’s named default.jpg.
All non single posts and category pages use the background_image added via the customizer.
# Step 2 – Install the ACF plugin and create a field named
acf_bg_img using the following settings as a guide.
- Change Background Color Based On Category
- Add Color Picker To Edit Category Screen To Set Color For Posts In Each Category