wp cli – How to run a custom WP cli command
I have existing code creating a custom WP cli command. The purpose of the code is to change a parent page for a custom post type. However, I don’t know how to read this code to understand what command exactly I should run to do this. I get the invalid parent error all the time.
So if I have a custom post type called event and I want to set all single events to have a parent page that has an ID of 12, what should I run?
<?php
$set_parents = function( $args = [], $assoc_args = [] ) {
$arguments = wp_parse_args( $assoc_args, array(
'post-type' => 'post',
'parent' => null
) );
if(is_null($arguments['parent']) && is_numeric(intval($arguments['parent']))) {
WP_CLI::error( " invalid parent ");
}
else {
$count = setParentsOnPostType($arguments['post-type'], $arguments['parent']);
WP_CLI::success( "$count ".$arguments['post-type']." -posts set to child of ".$arguments['parent'] );
}
};
function setParentsOnPostType($post_type, $parent_id = 0) {
$counter = 0;
$ok = true;
$args = [
'post_type' => $post_type,
'posts_per_page' => -1,
];
$query = new WP_Query($args);
if($query->have_posts()) { // if we have posts, then we update data
while($query->have_posts()) {
$query->the_post();
wp_update_post([
'ID' => get_the_ID(),
'post_parent' => $parent_id
]);
$counter++;
}
wp_reset_postdata();
}
return $counter;
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'set-parents', $set_parents );
}
I have tried several combinations like
wp set-parents post-type=event 12
wp set-parents post_type=event parent_id=12
wp set-parents event 12
But really, I have no idea what command I should use as I’m not really familiar with custom WP cli commands so I’m just guessing here.
Leave an answer