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

WordPress短码内容过滤求助:基于ACF字段的CPT年份筛选

解决短码按年份过滤自定义文章类型的问题

嘿,我来帮你搞定这个短码的过滤需求!其实核心就是在短码函数里接收并处理year参数,然后动态调整查询条件就行。我给你写好修改后的代码,你可以直接套用,记得替换成你自己的自定义文章类型名称和ACF字段名哦:

function speaker_overview_2017_shortcode( $atts ) {
    // 设置短码参数默认值,默认year为空表示显示全部
    $atts = shortcode_atts( array(
        'year' => '',
    ), $atts );

    // 构建查询参数
    $args = array(
        'post_type' => 'your_custom_post_type', // 替换成你的自定义文章类型名称
        'posts_per_page' => -1, // 显示所有符合条件的条目
        'orderby' => 'date', // 可以根据需要调整排序方式
        'order' => 'ASC',
    );

    // 如果传入了year参数,添加meta查询条件
    if ( ! empty( $atts['year'] ) ) {
        $args['meta_query'] = array(
            array(
                'key' => 'your_acf_year_field', // 替换成你的ACF年份字段名
                'value' => $atts['year'],
                'compare' => '=',
                'type' => 'numeric', // 因为年份是数字类型,指定类型更准确
            )
        );
    }

    // 执行查询
    $speaker_query = new WP_Query( $args );

    // 开始输出内容
    $output = '';
    if ( $speaker_query->have_posts() ) {
        $output .= '<div class="speaker-overview">';
        while ( $speaker_query->have_posts() ) {
            $speaker_query->the_post();
            // 这里替换成你自己的内容输出逻辑,比如获取ACF字段、文章标题等
            $speaker_name = get_the_title();
            $speaker_year = get_field( 'your_acf_year_field' ); // 同样替换成你的ACF字段名
            $output .= '<div class="speaker-item">';
            $output .= '<h3>' . esc_html( $speaker_name ) . '</h3>';
            $output .= '<p>年份:' . esc_html( $speaker_year ) . '</p>';
            $output .= '</div>';
        }
        $output .= '</div>';
        // 重置查询,避免影响后续全局文章数据
        wp_reset_postdata();
    } else {
        $output .= '<p>暂无相关演讲者信息</p>';
    }

    return $output;
}
// 注册短码
add_shortcode( 'speaker_overview_2017', 'speaker_overview_2017_shortcode' );

关键部分说明:

  • 用shortcode_atts给year参数设置了空字符串的默认值,这样不传参数时就会触发“显示全部”的逻辑。
  • 当year参数不为空时,我们在查询参数里添加了meta_query,精准匹配ACF字段的年份值,指定type为numeric是为了避免字符串匹配可能出现的误差(比如"2017"和2017的差异)。
  • 最后一定要加wp_reset_postdata()重置查询,防止影响页面后续的文章数据调用。

你只需要把代码里的your_custom_post_type换成你实际的自定义文章类型slug,your_acf_year_field换成你用ACF创建的年份字段名,再调整输出部分的HTML结构和内容到你需要的样子就可以了。这样:

  • 使用[speaker_overview_2017 year=2017]就只会显示2017年的条目
  • 使用[speaker_overview_2017 year=2018]显示2018年的条目
  • 直接用[speaker_overview_2017]就会显示所有年份的条目啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:54:26