我正在尝试在单个帖 subview 下方显示 3 个帖子(我设置了自定义帖子类型,因此希望此查询适用于所有单个帖子页面,无论帖子类型如何)。
但是,使用下面的代码我没有显示任何相关的帖子。当我删除 .'&exclude=' 时。 $current
我显示 3 个相关帖子,但当前帖子是其中之一。因此,为什么我添加了“排除”,但我不明白为什么当我添加它时它不显示任何内容。
如有任何帮助,我们将不胜感激。 谢谢
<?php
$backup = $post;
$current = $post->ID; //current page ID
global $post;
$thisPost = get_post_type(); //current custom post
$myposts = get_posts('numberposts=3&order=DESC&orderby=ID&post_type=' . $thisPost .
'&exclude=' . $current);
$check = count($myposts);
if ($check > 1 ) { ?>
<h1 id="recent">Related</h1>
<div id="related" class="group">
<ul class="group">
<?php
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark">
<article>
<h1 class="entry-title"><?php the_title() ?></h1>
<div class="name-date"><?php the_time('F j, Y'); ?></div>
<div class="theExcerpt"><?php the_excerpt(); ?></div>
</article>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php
$post = $backup;
wp_reset_query();
?>
</div><!-- #related -->
<?php } ?>
最佳答案
您可以使用 WP_Query 而不是使用 get_posts()
<?php
// You might need to use wp_reset_query();
// here if you have another query before this one
global $post;
$current_post_type = get_post_type( $post );
// The query arguments
$args = array(
'posts_per_page' => 3,
'order' => 'DESC',
'orderby' => 'ID',
'post_type' => $current_post_type,
'post__not_in' => array( $post->ID )
);
// Create the related query
$rel_query = new WP_Query( $args );
// Check if there is any related posts
if( $rel_query->have_posts() ) :
?>
<h1 id="recent">Related</h1>
<div id="related" class="group">
<ul class="group">
<?php
// The Loop
while ( $rel_query->have_posts() ) :
$rel_query->the_post();
?>
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark">
<article>
<h1 class="entry-title"><?php the_title() ?></h1>
<div class="name-date"><?php the_time('F j, Y'); ?></div>
<div class="theExcerpt"><?php the_excerpt(); ?></div>
</article>
</a>
</li>
<?php
endwhile;
?>
</ul><!-- .group -->
</div><!-- #related -->
<?php
endif;
// Reset the query
wp_reset_query();
?>
尝试上面的代码并根据您自己的需要进行修改。进行修改以适合您自己的标记。
关于WordPress - 显示 3 个相关帖子,无论帖子类型、自定义还是其他,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213667/