Wordpress:如何制作随机帖子,不包括当前和所选日期

时间:2015-07-09 10:08:26

标签: php wordpress

我需要在帖子页面上添加5个随机帖子(http://7cuteoutfits.com/2015/07/08/suits-rachel-z-office-fashion/),不包括当前帖子。随机帖子应该在选定的日期(例如从过去2个月到昨天的帖子) 我在wordpress的single.php中添加了几行代码,现在有5个随机帖子。所以我需要修改代码,以便它符合我的要求(上面)。我认为还有2行,如果你帮忙,我会非常感激。

<ul>
<?php
 $currentID = get_the_ID();
 $args = array(  'posts_per_page' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args);
foreach ( $rand_posts as $post ) : 
  setup_postdata( $post ); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; 
wp_reset_postdata(); ?>
</ul>

1 个答案:

答案 0 :(得分:1)

您可以使用WP_Query。

global $post;
$args = array(
'post__not_in' => array($post->ID)
'orderby'   => 'rand'
'date_query' => array(
    array(
        'after'     => 'January 1st, 2015',
        'before'    => array(
            'year'  => 2015,
            'month' => 07,
            'day'   => 9,
        ),
        'inclusive' => true,
    ),
),
'posts_per_page' => 5,
);
$query = new WP_Query( $args );

此查询在今天(包括)和2015年1月1日之间随机发布订单 我还没有在这里测试过这个片段,所以如果它不适合你,请告诉我。

有关WP_query及其用法的更多信息(也适用于日期参数)here

使用WP_Query查询后,您必须

wp_reset_postdata();
就像你现在一样。

修改

要显示帖子内容,您可以致电

the_content()

直接打印,或

get_the_content()

将其作为返回值。然后,您可以使用所需的HTML标记处理打印。