我有一个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/)完成的,但我无法让他们建议的代码在基本级别上工作,只按当前术语过滤。
这就是我到目前为止所知道的:
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');
这里可能有一个明显的错误,但我看不出来。
发布于 2021-10-25 01:00:12
尝试下面的代码。
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');
https://stackoverflow.com/questions/69705158
复制相似问题