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

WordPress事件短代码无文章时无法显示提示消息的问题

问题修复:自定义文章类型短码无数据时显示提示

原代码的核心问题

  1. 提示文本被错误放在了have_posts()为真的代码块内,逻辑完全颠倒
  2. 未处理category参数为空的情况,导致tax_query生成无效条件
  3. 错误使用wp_reset_query(),应该用wp_reset_postdata()恢复全局post变量

修正后的完整代码

add_shortcode('events', 'events');
function events($atts){
    $atts = shortcode_atts( array(
        'category' => ''
    ), $atts );

    $args = array(
        'post_type'     => 'event',
        'post_status'   => 'publish',
        'meta_key'      => 'event_date',
        'orderby'       => 'meta_value_num',
        'order'         => 'ASC',
        'posts_per_page'=> -1,
    );

    // 仅当category参数不为空时,添加tax_query条件
    if (!empty($atts['category'])) {
        $categories = explode(',' , $atts['category']);
        // 过滤掉空值,避免无效的分类slug
        $categories = array_filter(array_map('trim', $categories));
        if (!empty($categories)) {
            $args['tax_query'] = array( array(
                'taxonomy'  => 'category',
                'field'     => 'slug',
                'operator'  => 'IN', // 多分类用IN更合理,AND会要求文章同时属于所有分类
                'terms'     => $categories
            ) );
        }
    }

    ob_start();

    $my_query = new WP_Query( $args );
    if( $my_query->have_posts() ) {
        while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <div><?php the_title(); ?></div>
            <div><?php the_content(); ?></div>
        <?php endwhile;
        wp_reset_postdata(); // 恢复全局$post变量
    } else {
        // 无文章时显示提示
        echo '<p>* no events listed at this time...</p>';
    }

    $retVal = ob_get_contents();
    ob_end_clean();

    return $retVal;
}

修改说明

  • 调整提示文本位置:将提示文本移到else分支,确保只有查询不到文章时才显示
  • 处理空category参数:仅当category不为空时才添加tax_query,同时过滤掉分割后可能出现的空字符串,避免无效查询条件
  • 修改tax_query的operator:将AND改为IN,符合多分类筛选的常规需求(如果确实需要文章同时属于所有分类,可以改回AND)
  • 替换重置函数:用wp_reset_postdata()替代wp_reset_query(),这是自定义WP_Query的正确重置方式
  • 函数名统一:短码注册时的回调函数名Events改为小写events,保持和定义的函数名一致(PHP函数名不区分大小写,但统一风格更规范)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:48:30