I can’t get the post author ID outside the loop to make the get_the_author_meta work. So far I’ve tried different approaches:
1.
$author_id=$post->post_author;
2.
global $post;
$author_id=$post->post_author;
3.
$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;
4.
$author_id = $posts[0]->post_author;
I need the author ID to pass it on to:
$address = get_the_author_meta('user_email', $author_id);
Any suggestions?
The simplest and most straightforward way to get the post author ID outside the loop, if you know the post ID, is to use the WordPress core function
get_post_field()
.If you do not yet know the post ID of the page you are on, then since WP 3.1 the easiest thing to do is use the
get_queried_object_id()
(look for it in the list of Methods) function which works even outside the loop.If these do not work for you then please give a more detailed explanation of where you are trying to run your code and we can see if we can help further.
Hereâs how to obtain and get the author ID outside the WordPress loop:
Then it is possible to us
the_author_meta
:Depends on where you are. If you’re on a singular page (eg. only showing a single {{Insert Post Type Here}}), you could use
get_queried_object
, which will fetch the post object.If you’re anywhere else, you could use the global
$wp_query
object, and check its$posts
property. This should work on singular pages as well.You can also just “false start” the loop and rewind it to grab the author ID. This will no incur any additional database hits or the like. WordPress fetches all posts at once (at the time of writing).
rewind_posts
just resets the current post (the global$post
) object to the beginning of the array. The downside is that this may cause theloop_start
action to fire way earlier than you want it to — not a huge deal, just something to be aware of.This looks like it works outside of the loop, maybe this will help.
You could also manually set ID of post and grab this way:
Change ID out to post id manually for out of the loop access.
Not great solutions, but hopefully it helps.
I had the same issue here when trying to make a widget that displayed featured posts with author information.
I used some of the hint’s from @chrisguitarguy 2nd tip.
My code looked like this:
To obtain and get the author ID outside the loop:
Then use
remember if you are fetching posts id in loop and accessing author out side loop then it will only provide data of last post id in loop
Hopefully this wil help:
Why don’t you use the_author_meta
This can be used within the loop