26

I have a function retrieving ID's of posts by very specific means.

I need to be able to set the global $post in order to use functions like the_content(), which does not allow an ID as a parameter.

How can I achieve this?

1
  • 1
    What exactly do you mean with "set the global $post"? Could you please a) post the function retrieving the IDs and illustrate/sketch your use case?
    – kaiser
    Oct 10 '11 at 13:21
36

When your going through your loop add this:

global $post; 
$post = get_post( $ID, OBJECT );
setup_postdata( $post );

//Do something

wp_reset_postdata();
0
3

To work with posts outta loop try using:

get_post(post_id)

to get a post with a specific ID out of the loop,when you do this,the global object $post will hold the post which you'v just selected.Now you can get the content using :

$post->post_content .

check the get_post documentation on Wordpress Codex

1

A solution that works for me is:

  1. global $post; before the loop
  2. setup_postdata($post); inside the loop
  3. wp_reset_postdata(); after the loop

Take into account that the name of the variable must be $post

0

You may use a one-liner to reset the global post object.

setup_postdata( $GLOBALS['post'] =& $custom_post_object );

When you finish your template or loop be sure to reset the global post so you won't break other templates further down the stack.

wp_reset_postdata();

Note: PHPCS with WordPress standards will complain about overriding the global post so if you're using the WordPress standards you'll need to disable it for the line like so:

setup_postdata( $GLOBALS['post'] =& $post ); //phpcs:ignore

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.