Home › Forums › General Issues › 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
acf_add_local_field_group(array(
'key' => 'group_1',
'title' => 'Product Data',
'fields' => array(
array(
'key' => 'field_1',
'label' => 'Product',
'type' => 'tab',
'placement' => 'top',
'endpoint' => 0,
),
array(
'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.name, t.slug
FROM
wp_terms t
INNER JOIN
wp_term_taxonomy tax
ON
tax.term_id = t.term_id
WHERE
(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'];
acf_add_local_field(array(
'key' => 'field_1_' . $slug,
'label' => $name,
'type' => 'tab',
'placement' => 'top',
'endpoint' => 0,
'parent' => 'group_1',
));
acf_add_local_field(array(
'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. https://developer.wordpress.org/reference/functions/wp_get_object_terms/
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.