Can't reset query to show ramdom post after fi

2019-08-19 17:07发布

I have a piece of code to show a random post under a post. But this code only show me the post's write from the author of that post. Whats wrong?

    <!-- post -->
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> 

        <?php the_title(); ?>

        <?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?>
        <?php the_author(); ?>
        <?php the_category(none); ?>
        <?php the_date(); ?>


        <?php the_content();?>
        <?php $key="video"; echo get_post_meta($post->ID, $key, true); ?>
        <?php $key="imagen"; echo get_post_meta($post->ID, $key, true); ?>


    <?php endwhile; ?>

    <?php else : ?>

    <?php endif; ?>

    <!-- ramdom post -->

    <?php $posts = $posts = get_posts('orderby=rand&numberposts=3'); foreach($posts as $post) { ?>
       <?php the_post_thumbnail('photo-thumbnail') ?>
        <?php the_author(); ?>
        <?php the_category(none); ?>


    <?php } ?>

2条回答
smile是对你的礼貌
2楼-- · 2019-08-19 17:50

Replace the random post code with the code below. In your example you were querying 3 posts. If that's not your intention and you only want a single post replace 3 with 1 in posts_per_page.

$secondary_posts = new WP_Query( array( 'orderby' => 'rand', 'posts_per_page' => 3, 'no_found_rows' => 1, ) );
if ( $secondary_posts->have_posts() ) : while ( secondary_posts->have_posts() ) : $secondary_posts->the_post();

the_post_thumbnail( 'photo-thumbnail' );
the_author();
the_category();

endwhile; endif;

wp_reset_postdata();
查看更多
该账号已被封号
3楼-- · 2019-08-19 18:07

Try adding <?php wp_reset_query(); ?> after the first query.

查看更多
登录 后发表回答