Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active March 13, 2019 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/a8cf54a1d1bada84188d0253d84e8f34 to your computer and use it in GitHub Desktop.
Save davidsword/a8cf54a1d1bada84188d0253d84e8f34 to your computer and use it in GitHub Desktop.
WordPress convert post post_type to cpt based on post category
<?php
/**
* Implements `dsca` command.
*/
class DSCA_Helpers {
/**
* Change a custom post type.
*
* ## OPTIONS
*
* <post_type>
* : The custom post type to change.
*
* [--to=<new post type>]
* : The post type slug to change to
*
* ## EXAMPLES
*
* wp dscs changecpt books --to=posts
*
* @when after_wp_load
*/
function changecpt( $args, $assoc_args ) {
list( $post_type ) = $args;
$to = $assoc_args['to'];
$myquery = new WP_Query([
'post_type' => $post_type,
'post_status' => 'any',
'posts_per_page' => '-1'
// any additional tax or post_meta query here.
]);
foreach ( $myquery->posts as $apost ) {
wp_update_post( [
'ID' => $apost->ID,
'post_type' => $to // boom!
] );
WP_CLI::success( $apost->post_title . " - is now " . $to );
}
}
}
WP_CLI::add_command( 'dsca', 'DSCA_Helpers' );
// run with `wp dscs changecpt books --to=posts`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment