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 );
}
}