Skip Navigation

[Resolved] CRED taxonomy field: selection of parent terms – solution

This support ticket is created 7 years, 3 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+01:00)

This topic contains 1 reply, has 2 voices.

Last updated by Nigel 7 years, 3 months ago.

Assisted by: Nigel.

Author
Posts
#472846

I needed the same solution as asked here: https://toolset.com/forums/topic/cred-taxonomy-field-selection-of-parent-terms/

I found a simple solution for this one. Add this to your functions.php

Replace 'service' with the slug of your taxonomy.

/**
 * Set Parent Terms from Child Terms
 */


add_action('save_post', 'assign_parent_terms', 10, 2);

function assign_parent_terms($post_id, $post){

    // get all assigned terms   
    $terms = wp_get_post_terms($post_id, 'service' );
    foreach($terms as $term){
        while($term->parent != 0 && !has_term( $term->parent, 'service', $post )){
            // move upward until we get to 0 level terms
            wp_set_post_terms($post_id, array($term->parent), 'service', true);
            $term = get_term($term->parent, 'service');
        }
    }
}
#473040

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

For anyone else reading this, the above code will automatically add parent terms to a post where a child post has been added whenever a post is updated (i.e. via a front-end CRED form or in the admin pages), so if the user selects "Orlando" then the ancestor terms "Florida" and "USA" will automatically be added, too.

Note that the code runs whenever any kind of post is updated, it may make sense to add a conditional check that a particular post type that the taxonomy has been assigned to is being updated.

Thanks for sharing your solution!

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.