发布
社区首页 >问答首页 >按当前分类过滤ACF帖子对象

按当前分类过滤ACF帖子对象
EN

Stack Overflow用户
提问于 2021-10-25 08:51:05
回答 1查看 151关注 0票数 0

我有一个post Object字段,设置为在默认的Wordpress类别中显示。(在Wordpress中使用高级自定义字段)。

但是,我需要在这个字段上设置一个过滤器,以便只显示当前分类范围内的帖子。

因此,如果我在管理面板中的" Books“类别中,并单击post object字段,我应该只会看到Books类别中的文章。

这需要动态完成,因为相同的ACF post对象字段显示在每个类别分类中。

我认为这是使用acf/fields/post_object/query过滤器(根据这里的帖子:https://support.advancedcustomfields.com/forums/topic/dynamically-set-taxonomy-filter-for-post-object-field/)完成的,但我无法让他们建议的代码在基本级别上工作,只按当前术语过滤。

这就是我到目前为止所知道的:

代码语言:javascript
代码运行次数:0
复制
function filter_by_category( $args, $field, $post_id ) {
            
        // And adjust the query to filter by specific taxonomy term
        $args['tax_query'] = array(
            array(
                'taxonomy'  => 'category',
                'field'     => 'term_id',
                'terms'     => $post_id,
            ),
        );
    }
    return $args;
}

add_filter('acf/fields/post_object/query', 'filter_by_category');

这里可能有一个明显的错误,但我看不出来。

EN

回答 1

Stack Overflow用户

发布于 2021-10-25 09:00:12

尝试下面的代码。

代码语言:javascript
代码运行次数:0
复制
function filter_by_category( $args, $field, $post_id ) {
     
    // $post_id comes in here as term_# so we need to remove 'term_' to get the term ID
    $prefix = 'term_';
    
    // Also if you are creating a new taxonomy, post_id = 'term_0' so then there's no point in adding a filter
    if ( 'term_0' != $post_id && substr( $post_id, 0, strlen( $prefix )) == $prefix ) {
        // Set $term_id to the ID part of $post_id
        $term_id = substr( $post_id, strlen( $prefix ) );
        
        // And adjust the query to filter by specific taxonomy term
        $args['tax_query'] = array(
            array(
                'taxonomy'  => 'category',
                'field'     => 'term_id',
                'terms'     => $term_id,
            ),
        );
    }
    return $args;

}

add_filter('acf/fields/post_object/query', 'filter_by_category');
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69705158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档