0

I have a few custom posts that go from Parent to great grand children. I assign the parent post a term from a custom taxonomy that I would like for all of the child posts to inherit. Is there a way to do this? Or, could I make the child term pass up to the parent? Otherwise, I will have to apply the term to each post, which will be a very daunting task. Here is my structure:

-Staff Training, Student Curriculum, Resources, Training Plans (These are terms)
---Tracks (CPT)
------Topics (CPT)
---------Courses (CPT)
------------Resources (CPT)

As you can see, each resource has to be in a Course. Every Course has to be in a Topic. Every Topic has to be in a Track. And, every Track has a term from a custom taxonomy of Staff Training, Student Curriculum, Resources or Training Plan. Now, Training Plan is different in the fact that it will contain mostly just Resources that are put together and are already associated with another term. So, this means that some Resources will have more than one term. However, Tracks, Topics and Courses will only have one term.

I imagine that I will have to get all of the children of the parent CPT and apply the term that way. Or, maybe I apply it to the Resource and allow it to propagate upwards through the parents?

Any help you can afford would be great!

1

I haven't tested this extensively but it does work on both Publish and Update. When a post is Published or Updated it checks if a parent is set, grabs the parent to get all the parents taxonomies, then loops through and sets the children terms as the parents terms taxonomy by taxonomy.

/** Set Child Terms to Parent Terms **/
function set_parent_terms( $post_id, $post ) {
    if ( 'publish' === $post->post_status && $post->post_parent > 0 ) {
        $parent = get_post($post->post_parent);

        if(!empty($parent)){
            $taxonomies = get_object_taxonomies( $parent->post_type );
            foreach ( (array) $taxonomies as $taxonomy ) {
                $terms = wp_get_post_terms( $parent->ID, $taxonomy );
                if ( !empty( $terms ) ) {
                    $termArr = array_map(create_function('$obj', 'return $obj->term_id;'), $terms);
                    $tmp = wp_set_object_terms( $post_id, $termArr, $taxonomy, true );
                }
            }
        }
    }
}
add_action( 'save_post', 'set_parent_terms', 100, 2 );
  • Hey! I apologize for not replying for so long. My wife just had our son, so I have been out for some time. I tried the solution that you posted above and the logic seems correct, however, it is not applying the taxonomy as expected - nothing happens when I update the child post. – dericcain Sep 12 '14 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.