To fix all the older posts that you already posted with only the child term.
You need run this function only 1 time and its will add you the parents terms. its for all the ancestors of the child term.
Make sure to backup the DB before you run this function.
function fix_terms_parents() {
/**
* Create a query that select all the posts in your post type
*/
$query = new WP_Query(array('post_type' => 'property', 'posts_per_page' => -1));
if ( $query->have_posts() ):
while ( $query->have_posts() ) : $query->the_post();
$post_id = get_the_ID();
/**
* Get all the terms that set to the post
*/
$terms = get_the_terms($post_id, 'city-type');
foreach($terms as $term) {
/**
* Get the term ancestors and append them
*/
$ancestors = get_ancestors($term->term_id, 'city-type');
if($ancestors) {
$new_terms = wp_set_object_terms($post_id, $ancestors, 'city-type', true);
// the $new_terms variable is array of all the new terms that you set
}
}
endwhile;
wp_reset_postdata();
endif;
}
Here is a function to set all the term ancestors. you can use with the return that you get from wp_set_object_terms
in your old code.
/**
* @param int $post_id the post id
* @param string $taxonomy
* @param array terms ids
*
* @return array of the ancestors terms that was append
*/
function set_ancestors_terms($post_id, $taxonomy, $terms) {
foreach($terms as $term_id) {
$ancestors = get_ancestors($term_id, $taxonomy);
if($ancestors) {
// Append parent terms
return wp_set_object_terms($post_id, $ancestors, $taxonomy, true);
}
}
}
The first function you need to run only 1 time put it in the function.php and add add_action( 'init', 'fix_terms_parents', 10);
too before it to run it.
After this you can delete this function its only to fix the old posts.
Before you run the first function create DB backup.
The Second function you add too to the functions.php and you run it in your old code when you set the terms you need to get the return like this and run the function.
$terms_array = wp_set_object_terms($pid, $nhb_type_value, 'city-type');
set_ancestors_terms($pid, 'city-type', $terms_array);