donglaogu3788 2015-07-09 10:08
浏览 29
已采纳

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

I need to have 5 random posts on post page (http://7cuteoutfits.com/2015/07/08/suits-rachel-z-office-fashion/) excluding current post. Random posts should be on chosen dates (for example posts from last 2 months until yesterday ) I added a few lines of code to single.php of my wordpress and now have 5 random posts. So I need to modify the code so that it will meet my requirements (above). I think it's 2 more lines, I'll be very thankful if you help.

<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条回答 默认 最新

  • douaikuai2715 2015-07-09 10:27
    关注

    You can use WP_Query for that.

    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 );
    

    This query orders randomly posts between today (inclusive) and Jan. 1st 2015 I haven't tested the snippet here, so please let me know if it does not work for you.

    More info on WP_query and its usage (also for date parameters) here

    Once you query with WP_Query, you have to

    wp_reset_postdata();
    

    just as you are already doing.

    EDIT:

    To show the post content, you can call

    the_content()
    

    to print it directly, or

    get_the_content()
    

    to get it as a return value. Then you can handle the printing later with the HTML markup you desire.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi