Assign parent category to all posts that are already assigned to child category

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

enter image description here

Read More

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?

Related posts

1 comment

  1. 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();
    

Comments are closed.