1

Is there a way to remove the post editor with specific custom post meta?

Supposed that I have a key edit where a put the string "true" or "false" and I want to show the editor with true and hide with false, I used this code:

function my_remove()
{
  global $post;
  $edit = get_post_meta( $post->ID, '_edit', true  );

  if ($edit === 'false') {
    remove_post_type_support( 'post' , 'editor' );
  }
}
add_action('admin_init', 'my_remove');

I think the problem is that when admin_init fires there isn't a post yet, but if I use this function when I'm in a post, for instance by using $_POST value, I think I can't disable editor anymore...

Is there a way to do this?

  • Can you provide some more context, such as what problem this is trying to solve, and why? – Tom J Nowell Jun 29 '17 at 22:56
  • I want to use a private meta to enable and disable the content, cause I have page where I only use a template and I don't want that the client can change the content. For this I need a relationship between a custom meta value and the editor... – Salvio Jun 29 '17 at 23:25
1

You are right; admin_init is too early to use the global $post variable. Fortunately, the post id is passed to the URL when editing a post.

The following code will remove post type support for a post when the _edit meta key's value is set to the string false. There are checks in place to ensue this only happens if a post is being edited and it's a post post type.

/**
 * Removes support for editor when posts have the
 * _edit meta key set to false.
 */
add_action( 'admin_init', 'wpse_remove_editor' );
function wpse_remove_editor() {
    // Use $pagenow to determine what page is being viewed.
    global $pagenow;

    // Get the post ID and the action from the URL.
    $the_id = isset( $_REQUEST['post'] ) && $_REQUEST['post'] ? $_REQUEST['post'] : false;
    $edit_action = isset( $_REQUEST['action'] ) && 'edit' === $_REQUEST['action'] ? $_REQUEST['action'] : false;

    // Bail if we're not editing a post or we can't get the post ID.
    if ( 'post.php' !== $pagenow || ! $edit_action || ! $the_id ) {
        return;
    }

    // Get the post object using the post id.
    $the_post = get_post( $the_id );

    // Bail if we can't get the post object, or if it's not the post post type.
    if ( ! $the_post || 'post' !== $the_post->post_type ) {
        return;
    }

    // Get value for the _edit meta key.
    $use_editor = get_post_meta( $the_id, '_edit', true );

    // Disable editor if value is string "false". Note strict comparison. 
    if ( 'false' === $use_editor ) {
        remove_post_type_support( 'post' , 'editor' );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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