小心,只运行一次
$_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();