Selecting related posts

时间:2013-03-04 作者:user1684099

我正在用以下代码显示相关帖子:

<div class="my-related-posts"><h4>You may also be interested in...</h4><ul    
class="relatedposts">
<?php
$posts = get_posts(\'numberposts=4&orderby=rand&category=\'. $category->term_id 
. \'&exclude=\' . $current_post);
foreach($posts as $post) :
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?><br /><img     
src="<?php echo esc_url( $image[0] ); ?>" alt="View more info" /></a></li>
<?php endforeach; ?><?php endforeach; ?>
</ul>
</div> 
。。。但我想确保它显示帖子,即使没有其他同类帖子。。。比如说

if (less than 4 related posts) {
     display any other posts from other catagories
}
谢谢你的帮助。

1 个回复
最合适的回答,由SO网友:Michael 整理而成

如果没有4个相关帖子,下面的代码将用随机类别的随机帖子填充数字,并避免重复:

        <div class="my-related-posts"><h4>You may also be interested in...</h4><ul class="relatedposts">
<?php
$duplicates = array( $current_post );
$posts = get_posts( array( \'posts_per_page\' => 4, \'orderby\' => \'rand\', \'category\' => $category->term_id, \'post__not_in\' => array( $current_post )) );
$second_numbers = (!$posts) ? 4 : (4 - count( $posts ));
if( $posts ) :
    foreach($posts as $post) :
    setup_postdata( $post );
    $duplicates[] = $post->ID;
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
    ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?><br /><img src="<?php echo esc_url( $image[0] ); ?>" alt="View more info" /></a></li>
    <?php endforeach; wp_reset_postdata(); 
endif; 

if( $second_numbers >=1 ) : 
    $posts = get_posts( array(\'posts_per_page\' => $second_numbers, \'orderby\' => \'rand\', \'post__not_in\' => $duplicates ) );
    if( $posts ) foreach($posts as $post) :
    setup_postdata( $post );
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?><br /><img src="<?php echo esc_url( $image[0] ); ?>" alt="View more info" /></a></li>
    <?php endforeach; wp_reset_postdata(); 
endif; ?>

</ul>
</div>

结束

相关推荐

在WP_QUERY中为自定义分类设置POSTS_PER_PAGE

我使用下面的代码获取自定义分类术语下的所有页面,它显示了所有页面。我想要的是限制这一点,并且只说出在自定义分类法下发布的最后两页。posts\\u per\\u page=1在此处不起作用并显示所有页面。<?php $post_type = \'page\'; // Get all the taxonomies for this post type $taxonomies = get_object_taxonomies( (object) array( \'post