在我的Wordpress网站中,我的taxonomy-product-category.php
模板具有以下循环,用于将帖子加载到页面中:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
但是,我希望帖子是随机排序的,而不是遵循添加日期等特定顺序。
如何修改此循环以执行此操作?
您可以使用
pre_get_posts
来设置分类页面的随机顺序。请注意,随机排序会在分页页面之间重复帖子,因为每个页面都是一个新查询,而不是一个查询的扩展。不幸的是,这就是随机排序的工作方式。
您可以尝试以下操作
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only targets the front end
&& $q->is_main_query() // Only targets the main query
&& $q->is_tax( 'product-category' ) // Only targets the product-category tax pages
) {
$q->set( 'orderby', 'rand' );
}
});
更改:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
自:
<?php
$args = array(
'cat' => YOUR CATEGORY ID,
'post_type' => YOUR CUSTOM POST TYPE,
'orderby' => 'rand'
);
$query = new WP_Query($args);
?>
<?php if ($query->have_posts()) : ?>
<?php while ($query->have_posts()) : $query->the_post(); ?>