How to make Feature Image required for a Particular Template


For a particular post, I use a specific template (Story template) to display it. And any post with this particular template should have Featured Image.

I am using this snippet code to check if the item to be published is a post or a page. I would want to include if the user selects the template (Story template), s/he would need to add a featured image else the post would not be published.

add_action('save_story_post', 'check_featured_image');
add_action('admin_notices', 'featured_image_error');
function check_featured_image($post_id) {
    // Check if it is a post
    if(get_post_type($post_id) != 'post')
    if ( !has_post_thumbnail( $post_id ) ) {
        // set a transient to show the users an admin message
        set_transient( "has_post_thumbnail", "no" );
        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'check_featured_image');
        // update the post set it to draft
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
        add_action('save_post', 'check_featured_image');
    } else {
        delete_transient( "has_post_thumbnail" );
function featured_image_error()
    // check if the transient is set, and display the error message
    if ( get_transient( "has_post_thumbnail" ) == "no" ) {
        echo "<div id='message' class='error'><p><strong>You must select Featured Image. Your Post is saved but it can not be published.</strong></p></div>";
        delete_transient( "has_post_thumbnail" );
pensebien 4 months 0 Answers 17 views 0

Leave an answer