【问题标题】:Get Advanced Custom Field Group for specific taxonomy term获取特定分类术语的高级自定义字段组
【发布时间】:2019-11-21 16:15:18
【问题描述】:

我正在尝试为其分配的特定分类术语获取高级自定义字段组。我遇到过:

acf_get_field_groups();

很容易从帖子 ID 和分类中获得一个组,但是当我试图获得一个学期时,我没有运气;

试过这些:

acf_get_field_groups(array('term_id' => '1293'));

acf_get_field_groups(array('taxonomy' => 'services','term_id' => '1293'));

要么这个函数不能做我所期望的,要么我没有正确提供参数格式。

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    您尝试的逻辑本质上是“返回显示在具有 term_id xyz 的所有帖子上的所有字段组”。看起来像这样:

    $posts = get_posts(array(
      'numberposts' => -1,
      'tax_query' => array(
        array(
          'taxonomy' => 'post_tag',
          'field' => 'term_id',
          'terms' => 1, /// where term_id of term 1 is "1".
          'include_children' => false
        )
      )
    ));
    // Get the id's from every post.
    $post_ids = wp_list_pluck($posts, 'ID');
    // Combine them into a comma split string
    $post_ids = implode(',', $post_ids);
    // Fetch our field groups.
    $field_groups = acf_get_field_groups(array('post_id' => $post_ids))
    

    您还可以创建一个自定义的 ACF 过滤器来匹配它,这可能是最好和最有效的方法:

    add_filter('acf/location/rule_match/post_taxonomy',
        function ( $result, $rule, $screen ) {
    
            $value = acf_maybe_get( $screen, 'post_taxonomy' );
    
            // bail early if not taxonomy
            if( !$value ) return false;
    
            $match = ( $value == $rule['value'] );
    
            // Return.
            return $match;
    
        }
    , 10, 4);
    var_dump(acf_get_field_groups(array('post_taxonomy' => 'post_tag:test')));
    

    【讨论】:

    • 当您将位置设置为“如果 [Post Taxonomy] [is equal to] [term]”(可能这是一个 ACF PRO 功能)我可以使用 acf_get_field_groups(array('post_id' => $post_id); 轻松返回分配给帖子甚至特定帖子的字段组;我正在尝试返回字段组而不是帖子。到目前为止,我已经建立了一个解决方案是使用 acf_get_field_groups() 获取所有字段组;然后根据该对象中返回的位置参数过滤结果。
    • 我没有意识到是这样的。谢谢你通知我。关于最后一个示例......它不返回帖子......它根据要求返回字段组。它返回显示在具有术语的所有帖子上的所有字段组。这正是你所要求的。但是我会尝试提出一个原生的 acf_get_field_groups 解决方案,现在我知道 ACF 实际上有这种支持。
    • 抱歉再次阅读您的答案,我看到它返回 acf 组。在某些情况下,这样做的目的是我正在构建一个自定义休息路线,其中 acf 字段组将我的 term_id 分组,我的每个术语都有一个与之关联的组,我需要通过 ajax 即时获取一个组用户在表单中输入术语。
    • 酷我去看看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2015-02-22
    • 2014-09-04
    • 2016-07-01
    • 1970-01-01
    • 2017-08-28
    • 2017-01-04
    相关资源
    最近更新 更多