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

WordPress开发:根据event文章数量切换内容布局类名

WordPress 自定义文章类型数量判断类名逻辑实现

需求:当event自定义文章类型的已发布帖子数大于1时,内容容器使用类名event-container-multiple;仅1篇时使用类名event-container-single。

修改思路

借助WP_Query对象的found_posts属性获取符合条件的已发布帖子总数,根据总数判断要应用的容器类名,再循环输出内容。

修改后的完整短代码

add_shortcode( 'events', 'callback_function_name' );

function callback_function_name( $atts, $shrt_content = null ) {
    $atts = shortcode_atts(array(
        'category' => ''
    ), $atts, 'events');

    $categories  = ! empty( $atts['category'] ) ? explode( ',' , $atts['category'] ) : array();

    // 处理分类查询:无分类参数时移除tax_query,避免无效查询
    $query_args = array(
        'post_type'         => 'event',
        'post_status'       => 'publish',
        'meta_key'          => 'event_date',
        'orderby'           => 'meta_value_num',
        'order'             => 'ASC',
        'posts_per_page'    => -1
    );

    if ( !empty($categories) ) {
        $query_args['tax_query'] = array( array(
            'taxonomy'  => 'category',
            'field'     => 'slug',
            'operator'  => 'AND',
            'terms'     => $categories
        ) );
    }

    $post_query = new WP_Query( $query_args );
    ob_start();

    if ( $post_query->have_posts() ) {
        // 获取符合条件的帖子总数
        $total_posts = $post_query->found_posts;
        // 根据总数确定容器类名
        $container_class = $total_posts > 1 ? 'event-container-multiple' : 'event-container-single';
        ?>
        <div class="<?php echo esc_attr($container_class); ?>">
            <?php while ( $post_query->have_posts() ) : $post_query->the_post(); ?>
                <div class="event-item">
                    <?php the_title(); ?>
                    <?php the_content(); ?>
                </div>
            <?php endwhile; ?>
        </div>
        <?php
        wp_reset_postdata(); // 自定义WP_Query需用此函数重置,替代wp_reset_query()
    }

    $retVal = ob_get_contents();
    ob_end_clean();

    return $retVal;
}

关键修改点说明

  1. 总数获取:$post_query->found_posts能准确返回符合查询条件的已发布帖子总数,比循环计数更高效准确。
  2. 类名判断:用三元运算符根据总数直接确定容器类名,逻辑清晰简洁。
  3. 查询优化:无分类参数时移除tax_query,避免无效的空分类查询。
  4. 安全输出:用esc_attr()转义类名,避免XSS安全风险。
  5. 重置函数修正:自定义WP_Query应使用wp_reset_postdata(),wp_reset_query()仅适用于query_posts()的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:17:43