如何在wordpress中使用get_template_part()来使用get_post()来获取特定帖子?

cyp*_*r75 2 php wordpress wordpress-theming custom-wordpress-pages

我正在创建我的第一个wordpress主题.我正在使用循环和get_template_part()来显示我的帖子列表,如下所示:

while ( have_posts() ) {
    the_post();
    get_template_part( 'content', get_post_format() );
}
Run Code Online (Sandbox Code Playgroud)

这很好用,并将content.php作为post的模板加载.

我想在常规帖子输出的末尾使用get_template_part()显示特定的帖子.我添加了这个用于在我的while循环后用Id 123显示我的帖子:

get_post(123);
get_template_part( 'content', get_post_format() );
Run Code Online (Sandbox Code Playgroud)

所以总代码是:

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() );
Run Code Online (Sandbox Code Playgroud)

但这只是重复常规循环中的最后一个条目.有人可以帮忙吗?

谢谢和问候Jan

小智 6

这是工作解决方案:

global $post; 
$post = get_post(123); 
setup_postdata($post);
get_template_part( 'content', get_post_format() );
Run Code Online (Sandbox Code Playgroud)

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