简体   繁体   中英

How to display random posts in one single category in wordpress

I need to be able to randomize the posts in one single category. I have the following code at the moment in 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' );
    }
}

?>

But the problem is that it randomizes posts in all the categories. Can someone please help me with this and tell me how I can randomize posts only in category number 9?

You're using an assignment operator $catto->term_id = 9 in your conditional instead of a conditional operator like so: $catto->term_id === 9 .

Help you avoid these mistakes, yoda conditions will...

You can display posts from this category with two different ways write category name

<?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>  

Second way write category id for more information open this link random posts if you want display random posts from functions.php view the link random posts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM