When the new post which has no image published, save the specific image as the featured image ( by category )
As the title, I would like to save the post with the specific image as the featured image, when it is new published. Also I would like to save different images which is filtered by categories.
I have wrote the code below, it does not work as I wish to.
add_action('save_post', 'wp_force_featured_image', 20, 2);
function wp_force_featured_image($post_id, $post) {
if( $post->post_type == 'post' && $post->post_status == 'publish' ) {
if(!isset($_POST['_thumbnail_id'])) {
$categories = get_the_category( $post->slug );
if ( $categories = 'news' ) {
add_post_meta( $post_id, '_thumbnail_id', '3135' );
}
elseif ($categories = 'bi' ) {
add_post_meta( $post_id, '_thumbnail_id', '3138' );
}
}
}
}
I tried to get the category slug for comparing.
Any advises will help me a lot.
Thank you for your support in advance.
Solutions
If you're building a custom theme and you just want to have some fallback images, an easier approach might be to do something like this in your template:
<?php
if (has_post_thumbnail()) {
the_post_thumbnail();
} else if (in_category('news') {
echo wp_get_attachment_image('3135');
} else if (in_category('bi') {
echo wp_get_attachment_image('3138');
}
?>
Depending on what you're trying to do, this may or may not be a solution.
Your conditional is in trouble.
get_the_category()
returns an
object
, use foreach to find the specific category.
In addition, you assigned a value to the
$categories
variable, to compare you must use the
comparison operators
( Ex: == or === )
I refactored the code and adapted it to your case, I hope it helps.
add_action( 'save_post', 'wp_force_featured_image', 10, 3 );
function wp_force_featured_image( $post_id, $post, $update ) {
if ( $update ) {
return;
}
if ( $post->post_type !== 'post' ) {
return;
}
if ( $post->post_status !== 'publish' ) {
return;
}
$has_post_thumbnail = get_post_thumbnail_id( $post_id );
if ( ! empty( $has_post_thumbnail ) ) {
return;
}
$categories = get_the_category( $post_id );
$thumbnail_id = false;
foreach ( $categories as $category ) {
if ( $category->slug === 'news' ) {
$thumbnail_id = 3135;
break;
}
if ( $category->slug === 'bi' ) {
$thumbnail_id = 3138;
break;
}
}
if( $thumbnail_id ) {
add_post_meta( $post_id, '_thumbnail_id', $thumbnail_id, true );
}
}