Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use get_template_part() for specific post using get_post() in wordpress?

I am creating my first wordpress theme. I'm currently using loops and get_template_part() for displaying my post list like this:

while ( have_posts() ) {
    the_post();
    get_template_part( 'content', get_post_format() );
}

this works great and is loading the content.php as template for post.

I want to display a specific post using get_template_part() at the end of the regular posts output. I added this for displaying my post with Id 123 after my while loop:

get_post(123);
get_template_part( 'content', get_post_format() );

So the total code is:

while ( have_posts() ) {
    the_post();
    if($post->ID != 123) // exclude Post 123 from output
        get_template_part( 'content', get_post_format() );
}

get_post(123);
get_template_part( 'content', get_post_format() );

But this just repeats the last Entry from the regular loop. Can anyone help?

Thanks and regards Jan

like image 203
cypher75 Avatar asked Oct 19 '25 14:10

cypher75


1 Answers

Here is the working solution:

global $post; 
$post = get_post(123); 
setup_postdata($post);
get_template_part( 'content', get_post_format() );

https://codex.wordpress.org/Function_Reference/setup_postdata

like image 168
Siarhei Razuvalau Avatar answered Oct 22 '25 03:10

Siarhei Razuvalau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!