php - Wordpress query_posts orderby rand 在类别存档模板中不起作用

标签 php wordpress

我无法让我的 Wordpress 主题随机显示我在类别文件中显示的帖子 [我将其用作 CMS]。主页正常随机化,我 [我认为] 正确地改变了 WP_query。下面是确切的 args 数组:

array(4) { ["orderby"]=> string(4) "rand" ["order"]=> string(3) "ASC" ["posts_per_page"]=> string(2) "-1" ["category_name"]=> string(8) "branding" }

为了便于阅读,它是:

orderby => rand
order => ASC
posts_per_page => -1
category_name => branding (or whatever the query_string brings in)

我得到了该类别的所有帖子,但它们是按发布日期顺序排列的。

有什么线索吗?或在 have_posts 中改组我的 WP_query 结果的替代方法?

谢谢。

************EDIT************

抱歉,我应该更清楚上面的 args 数组。它是查询数组的 var_dump,而不是我添加到查询中的参数。

    $args = array(
        'orderby'        => 'rand',
        'order'      => 'ASC',
        'posts_per_page' => '-1',
    );
    global $wp_query;           
    remove_all_filters('posts_orderby');
    $theq = array_merge($args, $wp_query->query);
    query_posts($theq);

我按照 Sheikh Heera 的建议添加了 remove_all_filters,但并没有什么不同。

最佳答案

那么您最好创建一个新查询。这应该只用于分类模板,如 category.php 或 taxonomy-yourcustomtaxonomy.php。

global $wp_query;

$term = $wp_query->queried_object;

$args=array(
    'orderby' => 'rand',
    'posts_per_page' => -1,
    'post_type' => 'post',
    'tax_query' => array(
            array(
                'taxonomy'  => $term->taxonomy,
                'field'     => 'slug',
                'terms'     => $term->slug,
                )
            )
    );

$new_query = null;
$new_query = new WP_Query($args);

while ($new_query->have_posts()) : $new_query->the_post(); ?>
    <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <div class="entry-meta"><?php // Meta ?></div><!-- .entry-meta -->
        <div class="entry-content"><?php the_content(); ?></div>
    </div>
<?php
endwhile;
wp_reset_postdata();

关于php - Wordpress query_posts orderby rand 在类别存档模板中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10918814/

相关文章:

php - 在数据库中保存javascript代码

php - 不知道如何限制 PHP 中的内部 SQL 查询

php - 哎呀,看起来像出事了。尝试在内置服务器上运行时 Laravel 5 出现错误

php - 如何使用 SimplePie 过滤/阻止 RSS 提要项目

javascript - 如何创建一个按钮来模拟古腾堡富文本编辑器上的链接弹出窗口功能

php - 具有 WooCommerce 身份验证的 WordPress 自定义 API

css - 侧边栏不会向右浮动 wordpress

php - 具有自动增量的遗产

php - Mysql 分页 - 按 id 或时间?

javascript - 一个部分或 div 的 Wordpress block 主题 css