Code sur écran d'ordinateur

WordPress – Save parent categories in a selected category

It may happen that when you save your post, you want it to be considered not only in the chosen category but also in its parent category.

For example, you have the following categories:

– Auto
– – BMW
– – Audi

By selecting Audi you also automatically want to have the Auto category. To do this just use the save_post hook

/**** Add automatic parent category ******/
add_action("save_post","cf_save_parent_category");
function cf_save_parent_category($postid){
   // get parent post id
   $parent_post_id = get_post($postid)->post_parent;
   $parent_post_id = ($parent_post_id != 0) ? $parent_post_id : $postid;
   $current_categories = wp_get_post_categories($parent_post_id);
   foreach ($current_categories as $key => $category_id) {
      $ancestor_category = get_ancestors($category_id, 'category');
      foreach($ancestor_category as $ancestor_category_id){
         $current_categories[]=$ancestor_category_id;
      }
   }
   wp_set_post_categories( $parent_post_id, $current_categories ) ;
   $current_categories = wp_get_post_categories($parent_post_id);
}