怎么让wordpress随机文章不再随机变化

我用wordpress调用随机文章,下面的代码每次打开页面,随机文章都不一样,我想让文章产生的随机文章一次性随机生成后就不再变化了,请高手们帮我修改一下代码,好吗?万分感谢!代码如下:

   <?php $post_num = 4;
   $exclude_id = $post->ID;
    $posttags = get_the_tags();
    $i = 0;
    if ($posttags) {
        $tags = '';
        foreach ($posttags as $tag) $tags .= $tag->term_id . ',';
        $args = array('post_status' => 'publish',
            'tag__in' => explode(',', $tags),
            'post__not_in' => explode(',', $exclude_id),
            'ignore_sticky_posts' => 1,
            'orderby' => 'rand',
            'posts_per_page' => $post_num,
        ); query_posts($args);
        while (have_posts()) { the_post(); ?>
       <li>...</li>
      
阅读 1.7k
1 个回答

这个时候,可以通过临时增加个transient项,来保存首次获取到的随机日志id
示例代码:
image

    function transient_rand_post( $args ) {
        $transient_name = wp_hash(maybe_serialize($args));

        $result = get_site_transient( $transient_name );
        if ( !$result )  {
            $rand = new WP_Query($args);
            if ( count($rand->posts) ) {
                $result = array_column($rand->posts, 'ID');
                // 保持一个月不变
                set_site_transient($transient_name, $result, MONTH_IN_SECONDS);
            }
        }
        return $result;
    }

然后修改一下您的代码:

    $post_num = 4;
    $exclude_id = $post->ID;
    $posttags = get_the_tags();
    $i = 0;
    if ($posttags) {
        $tags = '';
        foreach ($posttags as $tag) $tags .= $tag->term_id . ',';
        $args = array('post_status' => 'publish',
            'tag__in' => explode(',', $tags),
            'post__not_in' => explode(',', $exclude_id),
            'ignore_sticky_posts' => 1,
            'orderby' => 'rand',
            'posts_per_page' => $post_num,
        ); 
        //query_posts($args);
        $rand_ids = transient_rand_post($args);
        query_posts(array('post__in' => $rand_ids));
        while (have_posts()) { the_post(); 
            the_title(); echo '<br />';
        }

这里面,rand_ids最好根据你的情况作一个事前判断。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进