修复您已发布的所有旧帖子,其中仅包含子术语。您只需运行此函数1次,它将为您添加父项。这是为所有的祖先的孩子术语。
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;
}
下面是一个设置所有术语祖先的函数。您可以使用从
wp_set_object_terms
在旧代码中。
/**
* @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);
}
}
}
第一个只需运行1次的函数将其放入函数中。php和add
add_action( \'init\', \'fix_terms_parents\', 10);
在它之前太多,无法运行它。在此之后,您可以删除此功能,它仅用于修复旧帖子。
在运行第一个函数之前,请创建DB备份。
您添加到函数中的第二个函数。php,当您设置需要的条件以获得这样的返回并运行函数时,您可以在旧代码中运行它。
$terms_array = wp_set_object_terms($pid, $nhb_type_value, \'city-type\');
set_ancestors_terms($pid, \'city-type\', $terms_array);