如何在wordpress中的单个类别中显示随机帖子

时间:2017-12-27 18:02:22

标签: php wordpress

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

    <?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类中随机化帖子吗?

2 个答案:

答案 0 :(得分:1)

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

帮助您避免这些错误,yoda conditions将......

答案 1 :(得分:-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以获取更多信息如果要显示来自functions.php的随机帖子,请打开此链接random posts,查看链接random posts