You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress开发:如何仅让指定分类文章随机展示

Solution for Conditional Post Sorting on WordPress Homepage

Got it, let's get this sorted for you! The goal is straightforward: randomize posts only for the decouvrir category, while keeping all others sorted by date (newest first). Here's how to adjust your code:

Step-by-Step Modification

Find the section where you create the WP_Query inside your category loop. We'll add a conditional check to switch the sorting logic based on the category slug.

Replace this original code block:

<?php $query = new WP_Query( array( 'posts_per_page' => $tab_num[$i][num], 'category_name' => $category->slug ) ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); get_template_part('content', $tab_num[$i][template]); endwhile; endif; ?>

With this updated version:

<?php
// Build base query arguments
$query_args = array(
    'posts_per_page' => $tab_num[$i]['num'], // Fixed array key syntax (added quotes for best practice)
    'category_name'  => $category->slug
);

// Apply random sorting only for "À découvrir" (decouvrir) category
if ( $category->slug === 'decouvrir' ) {
    $query_args['orderby'] = 'rand';
} else {
    // Explicitly set date descending for other categories (WordPress default, but explicit = clearer)
    $query_args['orderby'] = 'date';
    $query_args['order']   = 'DESC';
}

$query = new WP_Query( $query_args );

if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post();
        get_template_part('content', $tab_num[$i]['template']); // Fixed array key here too
    endwhile; 
endif;
?>

Key Notes:

  • Conditional Sorting: We check if the current category slug is decouvrir and add 'orderby' => 'rand' only for that case.
  • Explicit Date Order: For other categories, we explicitly set date descending. This is WordPress's default behavior, but writing it out makes your code more readable and prevents unexpected changes from themes/plugins that might alter default query settings.
  • Array Key Fix: Changed $tab_num[$i][num] to $tab_num[$i]['num'] (same for template). Unquoted array keys are treated as constants in PHP, which can cause errors if a constant with that name ever exists. Quoting them is standard best practice.

Full Updated Relevant Code Section

Here's how that part of your homepage template will look after the change:

<?php $i = 0; foreach( $categories as $category ) { if( ($category->count) >= 2 && $category->slug !== 'boutiques'){ $category_link = sprintf( '<a href="%1$s" alt="%2$s" class="link_tous">%3$s</a>', esc_url( get_category_link( $category->term_id ) ), esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ), esc_html( 'Voir tous' ) ); ?>
<div class="col-md-12">
<h2 class="cat-name"><?php echo $category->name ?></h2>
<?php echo sprintf( esc_html__( '%s', 'Voir tous' ), $category_link ); ?>
</div>
<ul class="sp-grid">
<?php
// Build base query arguments
$query_args = array(
    'posts_per_page' => $tab_num[$i]['num'],
    'category_name'  => $category->slug
);

// Apply random sorting only for "À découvrir" (decouvrir) category
if ( $category->slug === 'decouvrir' ) {
    $query_args['orderby'] = 'rand';
} else {
    // Explicitly set date descending for other categories
    $query_args['orderby'] = 'date';
    $query_args['order']   = 'DESC';
}

$query = new WP_Query( $query_args );

if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post();
        get_template_part('content', $tab_num[$i]['template']);
    endwhile; 
endif;
?>
</ul>
<?php if($i < 2){ $i++; }else{ $i = 0; } } } ?>

That's it! Now your homepage will show random posts for "À découvrir" and date-sorted (newest first) posts for all other categories.

内容的提问来源于stack exchange,提问作者pj06novo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:57:29