Cách buộc người dùng tải lên hình ảnh nổi bật trước khi xuất bản bài đăng trên wordpress

Việc cung cấp và thêm hình ảnh nổi bật vào bài đăng / trang WordPress không phải là một tùy chọn bắt buộc. Tuy nhiên nhiều người lại rất coi trọng vấn đề này nó khá liên quan đến vấn đề thẩm mỹ website – nhất là với một số theme nhất định nếu không có hình ảnh nổi bật sẽ rất mất thẩm mỹ. Cho nên trong hướng dẫn này, mình sẽ giới thiệu các mẹo về cách “Làm thế nào để buộc người dùng tải lên hình ảnh nổi bật trước khi xuất bản một bài đăng?”

1. Chèn mã dưới đây vào functions.php theme của bạn

// save_post is an action triggered whenever a post or page is created or updated
add_action(‘save_post’, ‘crunchify_verify_thumbnail’);
add_action(‘admin_notices’, ‘crunchify_show_thumbnail_error’);
 
function crunchify_verify_thumbnail($post_id) {
 
    // This applies to only type `post`. You could have this for `page` too
    if(get_post_type($post_id) != ‘post’)
        return;
    
    if ( !has_post_thumbnail( $post_id ) ) {
 
        // set a transient to show the users an admin message
        set_transient( “crunchify_check_thumbnail”, “no” );
 
        // unhook this function so it doesn’t loop infinitely
        remove_action(‘save_post’, ‘crunchify_verify_thumbnail’);
 
        // update the post set it to draft
        wp_update_post(array(‘ID’ => $post_id, ‘post_status’ => ‘draft’));
 
        add_action(‘save_post’, ‘crunchify_verify_thumbnail’);
    } else {
        delete_transient( “crunchify_check_thumbnail” );
    }
}
 
function crunchify_show_thumbnail_error()
{
    // Only show error message incase transient variable is set
 
    if ( get_transient( “crunchify_check_thumbnail” ) == “no” ) {
        echo “<div id=’message’ class=’error’><p><strong>Howdy. You wont be able to `Publish` this post until you select a `Featured Image`.</strong></p></div>”;
        delete_transient( “crunchify_check_thumbnail” );
    }
}
Bây giờ nếu như cố gắng xuất bản một bài đăng mà không có hình ảnh thu nhỏ – bạn sẽ thấy thông báo lỗi như thế này.

Nhưng với mã trên bạn vẫn có thể nhận được Post published sms. Với mã dưới đây, bạn sẽ có thể loại bỏ tin nhắn đó một cách dễ dàng.

// Simple way to Remove published post notice while error handled
add_filter( ‘post_updated_messages’, ‘crunchify_disable_publish_successful_msg’ );
function crunchify_disable_publish_successful_msg( $messages )
{
return array();
}

Be the first to comment

Leave a Reply

Your email address will not be published.


*