ACF教程:如何在Relationship查询中排除当前页面
解决ACF选项页Relationship字段前端展示时排除当前页面的问题
问题分析
你之前尝试的acf/fields/relationship/query过滤器仅作用于ACF后台选择Relationship字段时的查询逻辑,无法影响前端已选中页面的展示结果——因为你的字段存储在选项页(option)中,前端直接读取的是已选中的页面列表,后台过滤器对这部分内容没有作用。
解决方案一:前端循环时直接排除当前页面
这是最直接有效的处理方式,在遍历选中页面时,判断当前页面ID与循环项的页面ID是否一致,一致则跳过该条目:
<?php $coin_pages = get_field('sb_sector_pages_pages', 'option'); $current_page_id = get_queried_object_id(); // 获取当前页面的ID if( $coin_pages ): foreach( $coin_pages as $post ) : // 匹配到当前页面则跳过循环 if( $post->ID == $current_page_id ) continue; $permalink = get_permalink( $post->ID ); $thumbnail = get_the_post_thumbnail( $post->ID, 'full'); $title = get_the_title( $post->ID ); setup_postdata($post); ?> <li class="coin-article__sidebar-list-item"> <a href="<?php echo esc_url( $permalink ); ?>" class="coin-article__sidebar-list-link"> <div class="coin-article__sidebar-coin-ico"> <?php echo $thumbnail; ?> </div> <span class="coin-article__sidebar-coin-title"><?php echo esc_html( $title ); ?></span> </a> </li> <?php endforeach; wp_reset_postdata(); // 重置post数据,避免影响后续查询 endif; ?>
注:将原代码中的
esc_html($permalink)替换为esc_url(),符合WordPress链接转义的规范。
解决方案二:修正ACF过滤器(仅用于后台选页时排除当前页)
如果你的需求是在ACF后台选择Relationship字段时,自动排除当前正在编辑的页面,可以修正过滤器代码:
add_filter('acf/fields/relationship/query/name=sb_sector_pages_pages', 'exclude_current_page_from_relationship', 10, 3); function exclude_current_page_from_relationship( $args, $field, $post_id ) { // 仅在编辑普通页面时生效,跳过选项页本身的编辑场景 if( strpos($post_id, 'option') === false ) { $args['post__not_in'] = isset($args['post__not_in']) ? array_merge($args['post__not_in'], array($post_id)) : array($post_id); } return $args; }
该方案仅影响后台选页逻辑,不会改变前端已选中页面的展示——若核心需求是前端排除当前页,优先选择解决方案一。
内容的提问来源于stack exchange,提问作者Katharine Kulikova
相关产品推荐
相关产品推荐

