首页 > 解决方案 > 如何在 WordPress 中显示 5 个随机帖子?我的循环不工作?

问题描述

在我添加查询以进一步自定义我的循环之前,循环运行良好。我究竟做错了什么?

我试过添加 wp_reset_postdata(); 结束前 while & end 如果无济于事。除非我没有看到另一个问题?

    <?php
    $args = array(
        'orderby'        => 'rand',
        'posts_per_page' => '5',
    );
    $my_query = new WP_Query( $args );
    if ( $my_query->have_posts() ) {
        while ( $my_query->have_posts() ) {
            $my_query->the_post();

            get_template_part( 'template-parts/content/entry_cards', get_post_type() );

        } // end while
    } // end if

    ?>

我希望能够以随机顺序查看我的 5 个 WordPress 帖子(如我的数组中所述)。

标签: phpwordpresswordpress-theming

解决方案


我相信这一点:

$args = array(
    'orderby'        => 'rand',
    'posts_per_page' => '5',
);

应该:

$args = array(
    'post_type'      => 'post',
    'orderby'        => 'rand',
    'posts_per_page' => '5',
);

WP_Query()需要知道要提取什么样的数据。


推荐阅读