Archived topic
Fallback featured image from Category
9 replies · Started by Marco on October 29, 2021
Hello
I've added a category picture using ACF - so far so good.
I'd like to use this picture in case a post doesn't have a featured image set - is there a filter I could use to set this category image as featured image for the post - another use could be if a post belongs to a certain category, I'd like to show the category image?
Hope somebody can get me started on this.
Thank you
Hi Marco,
I would suggest to use a block element with dynamic features.
If you add a background image as the dynamic featured image for a container block, and toggles use fall back image, it will automatically use this background image as the fall back image.
For more info please check the below links:
https://docs.generatepress.com/article/block-element-page-hero/
https://docs.generatepress.com/article/block-element-content-template/
Thanks for replying - I hoped there was a filter I could hook in and add some code - I'm using elementor so those block elements probably won't work. maybe I could use the post_thumbnail_html filter if generatepress doesn't have a better filter?
I don't think GP has a specific filter for this, you can give post_thumbnail_html a try :)
You can have a look at this topic:
https://generatepress.com/forums/topic/default-fallback-featured-image/#post-505358
something like this actually works I'm just not sure whether this creates any issues:
function default_category_featured_image() {
global $post;
$featured_image_exists = has_post_thumbnail( $post->ID );
if ( in_category( '1', $post->ID ) )
set_post_thumbnail( $post->ID, '3031' );
}
add_action('the_post', 'default_category_featured_image');
Hi there,
what happens with that code if you add a featured image to that post ?
haven't tried it yet - have to play around with some different scenarios. have not find any other solution yet.
The method i prefer is the one that Ying linked to:
https://generatepress.com/forums/topic/default-fallback-featured-image/#post-505358
Not sure what issues the OP of that topic was having but i have used it many instances.
I tried that - problem is that the post_thumbnail_html filter does NOT work with Elementor and some plugins for Elementor
Your other code:
I believe the set_post_thumbnail hook fires on post save/updated, so i am not sure if that will work with the_post() hook. But i haven't used that hook before so i can't say for sure.
The other thing you would need in your condition is to check the $featured_image_exists is false:
if ( in_category( '1', $post->ID ) && $featured_image_exists == false )
Or it may just overwrite any exiting featured image....
But seeing as Elementor is doing its own thing you may be better of asking them if they have a filter or a different method to achieve this.