Home Forums General Issues Register fields for a CPT for each term in taxonomy


Register fields for a CPT for each term in taxonomy

  • Hi, I’m trying to create a group field for each term attached to this custom post.

    Like this:

    Say my CPT is for this product: Wood Panels and this can be used for Facade, Floors and Interiors (these are the selected terms).

    I need to create the field groups for each, but I tried to do this by PHP, I tried something like this:

    function create_field_groups() {
      global $wpdb;
      // general fields
      // everything goes ok here
        'key'    => 'group_1',
        'title'  => 'Product Data',
        'fields' => array(
            'key'       => 'field_1',
            'label'     => 'Product',
            'type'      => 'tab',
            'placement' => 'top',
            'endpoint'  => 0,
            'key'   => 'field_2',
            'label' => 'Short Description',
            'name'  => 'product_short_description',
            'type'  => 'wysiwyg',
          // etc...
        'location' => array(
          // etc...
      // querying DB to get terms in taxonomy
      $query = 'SELECT DISTINCT
        , t.slug 
                  wp_terms t 
                INNER JOIN 
                  wp_term_taxonomy tax 
                  tax.term_id = t.term_id
                  (tax.taxonomy = \'my_taxonomy\')';
      $terms = $wpdb->get_results($query, ARRAY_A);
      // if we get terms then create group fields for this term
      if ($terms) {
        foreach ($terms as $term) {
          $slug = $term['slug'];
          $name = $term['name'];
            'key'       => 'field_1_' . $slug,
            'label'     => $name,
            'type'      => 'tab',
            'placement' => 'top',
            'endpoint'  => 0,
            'parent'    => 'group_1',
            'key'    => 'field_2_' . $slug,
            'label'  => 'Short Description',
            'name'   => $slug . '_short_description',
            'type'   => 'wysiwyg',
            'parent' => 'group_1',
          // etc...
    add_action('acf/init', 'create_field_groups');

    With this function I can generate the first part of the fields, but when I try to create the terms fields instead of getting four different tabs, I just get one from the last term.

    How can I fix this?

  • I do not know of you’ve figured this out yet or not, but I don’t see anything wrong in your add_local_field() code. The only thing I can come up with is that your query is not returning what you think it should be returning.

    I would try using wp_get_object_terms() rather than a custom query.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.