WordPress – Save parent categories in a selected category

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

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 hook save_post

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!)? $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);
}

Leave a Reply