WordPress Code to get Author ID by Post ID –
WordPress provides get_post_field($field, WP_Post $post=null, $context = ‘display’) function to get Author id by post id.
This function accepts 3 parameters –
$field – (String – Required) Post field name that we want to get.
$post – (Int/Post Object – Optional). Its default value is null. We can pass the parameter for reference. Like in our example, we want to get Author id based on Post id, so we can pass post id in this parameter.
$context – (String – Optional) – It is used to define the way to filter the data. It can accepts ‘raw’, ‘edit’, ‘db’, or ‘display’. Its default value is ‘display’.
To get author id, you can use the function by passing post_author and post id as parameter where post_author is the column(in the database) for Author id that we want to get and post id is for reference of Author id(Based on which we want to get author id).
$author_id = get_post_field( ‘post_author’, $post_id );
Note: The function returns the value of the post field on success and empty string on failure.