1 comment

  1. Through a lot more research and some trial and error, I figured out the correct code to use that will restrict a post from being edited based on the user ID AND a custom meta field.

    $user = get_current_user_id();
    $super_users = array(1);
    

    The first two pieces of code within the function are important for restricting users from editing/deleting base on their user ID. 1 being the primary admin. You can always expand the array to include additional users based on their ID.

    It’s easier to provide access and block everyone else rather than block certain users. This way new users don’t accidentally get access to editing/deleting specific posts.

    global $post;
    

    In order to grab the information from custom field, you need to define $post, and use the following code to grab the fields from the array.

    $customstatus = get_post_meta( $post->ID, 'protected_value', true );
    

    I adjusted the if statement so that rather than restricting certain users, it only allows the users defined by $super_users using the following code:

    if(!in_array($user, $super_users) && $customstatus == 'Protected'){
                do_action('admin_page_access_denied');
                wp_die( __('You cannot modify or delete this entry.') );
                exit;
            }
    

    The code will return the with the admin_page_access_denied with a line of text stating that the post cannot be edited or trashed. You then add the following actions for what the restrict_post_deletion affects.

    add_action('edit_post', 'restrict_post_deletion', 10, 1);
    add_action('wp_trash_post', 'restrict_post_deletion', 10, 1);
    add_action('before_delete_post', 'restrict_post_deletion', 10, 1);
    

    Here is the full code that goes into your themes functions.php

    function restrict_post_deletion(){
        $user = get_current_user_id();
        $super_users = array(1);
        global $post;
    
        $customstatus = get_post_meta( $post->ID, 'protected_value', true );
    
        if(!in_array($user, $super_users) && $customstatus == 'Protected'){
            do_action('admin_page_access_denied');
            wp_die( __('You cannot modify or delete this entry.') );
            exit;
        }
    }
    add_action('edit_post', 'restrict_post_deletion', 10, 1);
    add_action('wp_trash_post', 'restrict_post_deletion', 10, 1);
    add_action('before_delete_post', 'restrict_post_deletion', 10, 1);
    

Comments are closed.