Skip to content

Instantly share code, notes, and snippets.

@djp424
Created October 13, 2015 14:54
Show Gist options
  • Save djp424/ff671cd3edfaff2ba6aa to your computer and use it in GitHub Desktop.
Save djp424/ff671cd3edfaff2ba6aa to your computer and use it in GitHub Desktop.
Creates categories based on cpt (parent posts only) with WordPress
<?php
// creates categories based on cpt (parent posts only)
function create_categories_based_on_ctp() {
// cpt you are coping posts from
$cccpt_posts = array( 'post_type' => 'ctp', 'posts_per_page' => -1 );
$cccpt_postslist = get_posts( $cccpt_posts );
// cpt you are adding categories to
$cccpt_cpt_destination = ''; // example: 'communites'
$cccpt_cpt_description_description = ''; // example: 'this is for communities'
foreach ( $cccpt_postslist as $post ) : setup_postdata( $post ); ?>
<?php
$ctp_post_parents = get_post_ancestors( $post->ID );
// check if the post is not a parent
if( $ctp_post_parents == null ) {
// create category bassed off of post title
wp_insert_term(
esc_html( $post->post_title ),
$cccpt_cpt_destination,
array(
'description' => $cccpt_cpt_description_description,
'slug' => basename( get_permalink( $post->ID ) )
)
);
}
?>
<?php endforeach;
wp_reset_postdata();
}
add_action( 'admin_footer', 'create_categories_based_on_ctp' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment