[英]Wordpress - display 3 related posts regardless of the post type, custom or otherwise
I'm trying to display 3 posts below my single post view (I have custom post types set up so want this query to work on all single post pages regardless of the post type). 我正在尝试在我的单个帖子视图下方显示3个帖子(我设置了自定义帖子类型,因此希望此查询在所有单个帖子页面上都可以使用,而不管帖子类型如何)。
However with the code below I don't get any related posts displayed. 但是,使用下面的代码,我不会显示任何相关帖子。 When I removed .'&exclude=' . $current
当我删除.'&exclude=' . $current
.'&exclude=' . $current
I get 3 related posts display but with the current post being one of them. .'&exclude=' . $current
我得到3条相关的帖子显示,但当前帖子是其中之一。 Hence why I added 'exclude' but I don't see why its not displaying any when I add this in. 因此,为什么我添加了“排除”,但看不到为什么在添加时不显示任何内容。
Any help would be appreciate. 任何帮助将不胜感激。 Thanks 谢谢
<?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 } ?>
Instead of using get_posts(), you could use WP_Query 除了使用get_posts(),还可以使用WP_Query
<?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();
?>
Try out the code above and modify it for your own need. 试用上面的代码,并根据自己的需要对其进行修改。 Modified to suit your own markup. 修改以适合您自己的标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.