0

So I am looking at adding some custom post_meta to posts and I want those posts to not be editable, which will be some content that I am pulling in.

Here is what I have:

I have solved the issues when visiting the Post post_type and attempting to edit a post with a specific post_meta using this (This works great in the UI):

add_filter('post_row_actions', function($actions, $post) {
    if (get_post_meta($post->ID, 'global_post', true)) {
        unset($actions['edit']);
        unset($actions['inline hide-if-no-js']);
    }

    return $actions;
}, 10, 2);

The above hides the "edit" and "quick edit" buttons for posts with specific post_meta in the UI.

However, when visiting the edit link directly (Example: https://example.com/wp-admin/post.php?post=19771&action=edit - I was still able to edit the post.

Is there a way that I can prevent a post from being edited when visiting a link directly? I was able to successfully hide the buttons in the UI, but this would also be helpful.

1 Answer 1

1

I think an elegant way to accomplish this would be to hook into map_meta_cap and deny users as though they do not have the capability to edit the post. This should also gate any other potential work-arounds, such as modifying the post through the REST API or direct POSTing. As an added benefit, it will also take care of omitting the edit links such that you don't need to include your current solution.

add_filter( 'map_meta_cap', 'wpse405452_restrict_global_post_editing', 10, 4 );

function wpse405452_restrict_global_post_editing( $caps, $cap, $user_id, $args ) {
  if( $cap !== 'edit_post' )
    return $caps;
  
  $post_id = $args[0];

  if( get_post_meta( $post_id, 'global_post', true ) )
    $caps[] = 'do_not_allow';
    
  return $caps;
}

An introduction to roles & capabilities can be found in the Plugin Developer Handbook

3
  • Thanks so much @bosco, I will be trying this attempt as soon as I get home and testing it out! First time hearing about this hook.
    – Sem
    May 5 at 20:06
  • So I just attempted this and it works great, but the posts that I am pulling in are set are 'pending' status and with this integration, I'm not able to change the status of the post to published when needed, would there be a workaround or could I just keep quick edit available? Otherwise, this is awesome.
    – Sem
    May 5 at 20:17
  • There are a lot of possibilities! The easiest would probably be to hardcode an exemption for your user or the admin role or some such - or add a new role to your user and exempt that. I suppose you could also exempt posts with pending status... Or maybe just add a link in post_row_actions for certain roles which allows you to toggle the status between pending and publish?
    – bosco
    May 5 at 20:34

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.