2017-12-27 921 views
0

我需要能够在一个单一类别中随机化帖子。我目前在functions.php中有以下代码:如何在wordpress中的单一类别中显示随机帖子

<?php 

add_action('pre_get_posts', 'generate_random_category_posts', 100); 
function generate_random_category_posts($query) { 
    $catto = get_queried_object(); 
    if ($query->is_category() && $query->is_main_query() && $catto->term_id = 9) { 
     $query->set('orderby', 'rand'); 
    } 
} 

?> 

但问题是它会随机化所有类别中的帖子。有人可以帮助我,并告诉我如何只能在类别9中随机化帖子?

+0

你是否在使用类别或定制分类术语? –

+0

如果是类别尝试: query_posts(阵列( '的OrderBy'=> '兰特', '猫'=> 9, 'posts_per_page'=> 1 )); –

回答

1

您在条件中使用赋值运算符$catto->term_id = 9,而不是如此的条件运算符:$catto->term_id === 9

帮助你避免这些错误,yoda conditions意志......

+0

哇,现在它工作。我对这个错误感到非常惭愧,并希望我今后的问题不会那么愚蠢。非常感谢您为我展示正确的方向。 –

-1

你可以用两种不同的方式显示来自这一类的帖子写的类别名称

<?php 
    // write category name that you will display it 
$the_query = new WP_Query(array ('orderby' => 'rand', 'posts_per_page' => '5' ,'category_name'=>'your_category_name')); 
            // output the random post 
            while ($the_query->have_posts()) : $the_query->the_post();?> 
             <li> 
             <a href="#"> 
              <?php the_post_thumbnail(); 
              ?> 
             </a> 
             <h3><a href="<?php echo esc_url(get_permalink()); ?>"><?php echo limit_word_count(the_title()); ?></a></h3> 
            <div class="meta-post"> 
             <a href="<?php echo the_author_link(); ?>"> 
              <?php the_author(); ?> 
             </a> 
             <em></em> 
             <span> 
              <?php echo get_the_date('d M Y'); ?> 
             </span> 

            </div> 
           </li> 

方式二写类别ID为更多信息,打开此链接random posts如果你想显示来自functions.php的随机文章查看链接random posts

+0

非常感谢。但是定制循环的问题是分页问题。你能告诉我任何如何使用自定义循环分页代码示例吗? –

相关问题