0

I need to take the ID of the post that is loaded in the dashboard for editing. get_the_ID or get_queried_object() seems to not work, even if this functions are supposed to be used also outside the loop.

I need the post ID to prevent a role from editing this post in the dashboard, so I can do something like: if the post that the user attempt to load has the ID == 9, redirect the user to the dashboard home or die.

So, how can I get the ID of the current post that the user attempt to load?


Edit: The following is one of the piece of code I tried. If the role is matched, the user is in the dashboard and the post has the category ID == 20 (assuming that has_category take the current post if an ID is not specified), then die.

    add_action('admin_init', 'bck_restrict_post');
    function bck_restrict_post() {
        if (current_user_can('myrole') && is_admin() && has_category(20) ) {
        wp_die();
      }    
   }

It's very simple, but has_category doesn't work. It doesn't take the current post ID and nothing change. I've also tried using in_category(); same result.

  • A general answer wouldn't be hard to provide, but I think you'll get something more useful, and possibly explaining why you're getting unexpected results, if you provide a full example of the code you're trying to use. – CK MacLeod Oct 30 '16 at 20:15
  • Added an example. – BlackOut Oct 30 '16 at 20:40
0

Here's a simple example that redirects to the edit posts screen. Since what you're asking for is how to get the post, I'm not bothering with messages or particular redirect pages or other variables - though note that wp_die() will just kill the page. In my tests, it just gets you a blank one.

Anyway, I think the two things you need are the load-(page) hook and the ID from the $_GET variable when editing posts:

add_action( 'load-post.php', 'redirect_post_x' ) ;

function redirect_post_x() {

    //if post ID = 99999: ID not cast as int here
    if ( $_GET[ 'post' ] === '99999' ) {

        wp_redirect( admin_url( 'edit.php' ) );
        exit;

    }

}

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.