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

ACF Repeater字段关联地点ID筛选艺术家演出信息求助

解决方案

你的代码已经能正确筛选出在当前地点有演出的艺术家,但问题出在循环输出时,没有过滤掉艺术家其他地点的演出记录。以下是修正后的实现方案:

修正后的single-place.php代码

<?php
function allow_wildcards($where)
{
    global $wpdb;
    $where = str_replace(
        "meta_key = 'representation_%",
        "meta_key LIKE 'representation_%",
        $wpdb->remove_placeholder_escape($where)
    );

    return $where;
}

add_filter('posts_where', 'allow_wildcards');
?>
<?php
$current_place_id = get_the_ID();
$query = new WP_Query(array(
    'post_type' => 'artiste',
    'meta_query' => array(
        array(
            'meta_key' => 'representation_%_lieu_representation',
            'value' => '"'.$current_place_id.'"',
            'compare' => 'LIKE',
        ),
    ),
));
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
    <?php if (have_rows('representation')): while (have_rows('representation')) : the_row(); ?>
        <?php
        // 获取当前演出行关联的地点ID,仅输出与当前页面匹配的行
        $lieu_id = get_sub_field('lieu_representation');
        if ($lieu_id == $current_place_id):
        ?>
            <p>
                <?php $date_rep = get_sub_field('date_representation'); ?>
                <?php echo $date_rep; ?> | <?php the_title(); ?>
            </p>
        <?php endif; ?>
    <?php endwhile; else : endif; ?>
<?php endwhile; else: endif;
wp_reset_postdata();
// 移除过滤器,避免影响后续查询
remove_filter('posts_where', 'allow_wildcards');
?>

关键修改说明

  • 新增$current_place_id变量存储当前地点ID,提升代码可读性
  • 在Repeater字段循环中,通过get_sub_field('lieu_representation')获取当前行的地点ID,与当前页面ID对比,仅保留匹配的演出记录
  • 末尾添加remove_filter操作,防止自定义过滤器影响页面后续的WP_Query查询

适配Post Object类型字段的补充说明

如果你的lieu_representation是Post Object类型(直接关联地点文章),get_sub_field会返回WP_Post对象,此时需要调整ID对比逻辑:

$lieu_post = get_sub_field('lieu_representation');
if ($lieu_post->ID == $current_place_id):

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:10:11