0

I want to do following...

1 - Publish the new post, 2 - Check if this new post has a featured image, 3 - If it has not a featured image, define its category and save the specific prepared image as the featured image. = Preparing different images for each categories.

Please have a look at the following code that I am using in my functions.php. but it is not working for me.

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'])) {

         $post_categories = get_the_category( $post->ID );
         $cats = $post_categories->term_id;

         if ( $cats = 1 ) {      
          add_post_meta( $post_id, '_thumbnail_id', '3135' );
         }
         elseif  ( $cats  = 2 ) {
          add_post_meta( $post_id, '_thumbnail_id', '3138' );
         }
    }
    }
}
2

1 Answer 1

1

I suggest that you install FPW Category Thumbnails plugin. It will cover every scenario mentioned in your question. It will save you from maintaining code in functions.php, and will do it visually! The built-in FPW Post Thumbnails will add very powerful styling to your featured images (borders, shadows, margins, backgrounds, etc). You will be able to switch themes without losing its functionality!

Your code (if you want to use it) needs 4 changes to work. Replace:

if(!isset($_POST['_thumbnail_id'])) {

with

if(-1 == $_POST['_thumbnail_id']) {

and replace:

$cats = $post_categories->term_id;

with

$cats = $post_categories[0]->term_id;

In lines checking category id, change assign operator = to comparison ==.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.