1

All my website's posts are assigned to subcategories, but not to their parent categories too:

enter image description here

Is there someway that I could massively assign posts to their parent categories too?

enter image description here

My website has more than 3k posts, so I need to find a quick way to do this. I didn't find any plugin that could help me. Any suggestions please?

0

be careful and only run it once

$_query = new WP_Query( array(
    'post_type' => 'post',
    'posts_per_page' => -1,
 ) );
function complete_parent_category( $term_id, $dep=array() ) {
    $category = get_term( $term_id, 'category' );
    $dep[ $category->term_id ] = $category->slug;
    if( $category->parent ) {
      $dep = complete_parent_category( $category->parent, $dep );
    }
    return $dep;
}
echo '<pre>';
while( $_query->have_posts() ) {
  $_query->next_post();
  echo '<br /><strong>'.$_query->post->post_title .'</strong> |>> ';
  $cat_post = array();
  $cats = get_the_category( $_query->post->ID );
  if( count( $cats ) ) {
    foreach ($cats as $cat) {
      $cat_post[ $cat->term_id ] = $cat->slug;
      if( $cat->parent == 0 ) continue; 
      $category_object = get_term( $cat, 'category' );
      $cat_post = complete_parent_category( $cat->parent, $cat_post );
    }
  }
  if( count( $cats ) == count( $cat_post ) ) return;
  $data = array(
      'ID'           => $_query->post->ID,
      'post_category' => array_keys($cat_post),
  );
  wp_update_post( $data );
}

wp_reset_postdata();

exit();
| improve this answer | |
  • where should I place this code? In a seperate file? In index.php? – ktsixit Feb 17 '14 at 14:01
  • It would be useful to describe a technique for a “one-shot” plug-in and also for automatically ticking parent categories for new posts or when category assignments are edited. – Andy Macaulay-Brook Mar 15 '19 at 21:23

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.