1

Currently able to display the post author ID on the frontend with no difficulties. Returning the ID in /wp-admin when editing a post is proving to be tricky. Here's what I have so far:

$current_user_id = get_current_user_id(); // Get the current users ID
$author_id = get_post_field ('post_author', $post_id); // Get the author ID

if( is_user_logged_in() && $current_user_id == $author_id ) { 
    // wp-dashboard script
}

I've tried a handful of other methods for getting the user ID with no success. Displaying $current_user_id through the theme's functions.php file worked without issues along with other PHP code. Perhaps the ID isn't being loaded when functions.php loads?

3
  • In which action hook you are trying to do this? Jun 10, 2019 at 7:59
  • I think you don't need to use is_user_logged_in() because get_current_user_id() return 0 for non logged in user. Jun 10, 2019 at 8:03
  • I should have clarified that I'm using this for the plugin co-authors plus so that I can allow authors to assign other authors. After placing an edit_cap filter: github.com/Automattic/Co-Authors-Plus/issues/… The problem was that co-authors could take over a given post from the original author. As a result I needed a way to have the add_filter to execute only if the page author is viewing the post. Jun 10, 2019 at 17:51

1 Answer 1

1

It can be done like this without having to rely on the $post global.

if ( is_admin() ) {
    if( isset( $_GET['post'] ) && isset( $_GET['action'] ) && $_GET['action'] === 'edit' ) {
        $post_id = $_GET['post'];
        $current_post = get_post($post_id);
        $author_id = $current_post->post_author;
    } 
}

The query string variable post is always the post_id you are editing and additionally you need to check if the action query variable is set and it equals to edit.

Additionally you can explore the get_current_screen() function to setup more advanced conditionals for better security.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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