开发者

Wordpress get_posts() returning same post all the time

开发者 https://www.devze.com 2023-04-12 19:49 出处:网络
I am just playing around with WordPress and neither I have any idea abt PHP. I am trying to fetch few random posts using get_posts() function of the WordPress

I am just playing around with WordPress and neither I have any idea abt PHP. I am trying to fetch few random posts using get_posts() function of the WordPress my code is something like this

<?php
    args1 = array( 'numberposts' => 12 ,'orderby' => 'rand');
    $rand_posts1 = get_posts( $args1);
            foreach( $rand_posts1 as $randpost1 ) : ?> 
                <?php the_title(); ?>
                     <?php endforeach; ?>

But this code is only returning same post all the 12 times and that is the la开发者_开发百科stest post. I am clueless what exactly I am doing wrong.

Can any one help me to correct my mistake or point me about my issue.


Try this one

       <?php
            $args1 = array( 'numberposts' => 12 ,'orderby' => 'rand');
            global $post;
            //save the current post
            $temp=$post;
            $rand_posts1 = get_posts( $args1);

            foreach( $rand_posts1 as $post ) ://yes this is required, we need $post in setup_postdata
                setup_postdata($post);    ?> 
                <?php the_title(); ?>

            <?php endforeach; 

            $post=$temp;//restore current page

            ?>

That will do it. Also please take a look at get_posts

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号