Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created September 13, 2020 15:40
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 yanknudtskov/93f979abcdad9be3846299c90fa3be8f to your computer and use it in GitHub Desktop.
Save yanknudtskov/93f979abcdad9be3846299c90fa3be8f to your computer and use it in GitHub Desktop.
Creating a custom WP CLI command
<?php
/*
Plugin Name: Yan&Co complete orders CLI command
Plugin URI: https://www.yanco.dk/
Description: Complete virtual orders CLI command
Author: Yan&Co
Version: 1.0.0
Author URI: https://www.yanco.dk/
*/
class YANCO_CLI {
/**
* Completes Virtual Orders
*
* @since 0.0.1
* @author Yan Knudtskov
*/
public function complete_virtual_orders() {
$args = array(
'post_status' => 'wc-processing',
'post_type' => 'shop_order',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if( !empty( $query->posts ) ) {
$progress = \WP_CLI\Utils\make_progress_bar( 'Completing Orders', count( $query->posts ) );
foreach( $query->posts as $post ) {
$only_virtual = true;
$order = wc_get_order( $post->ID );
$order_items = $order->get_items();
foreach( $order_items as $order_item ) {
$product_id = $order_item->get_product_id();
if( $product_id ) {
$product = wc_get_product( $product_id );
if( $product ) {
if( $product->is_virtual() == false ) {
$only_virtual = false;
}
}
}
}
if( $only_virtual == true ) {
$order->update_status('completed');
// usleep(250000); // Wait for 0,25 seconds
}
$progress->tick();
}
$progress->finish();
WP_CLI::success( count( $query->posts ) . ' orders completed!' ); // Prepends Success to message
}
}
}
/**
* Registers our command when cli get's initialized.
*
* @since 1.0.0
* @author Yan Knudtskov
*/
function yanco_cli_register_commands() {
WP_CLI::add_command( 'yanco', 'YANCO_CLI' );
}
add_action( 'cli_init', 'yanco_cli_register_commands' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment