Save a dynamic global value related to Woocommerce orders in database

The main task is to save the value in a common metadata store. Then can get it on any created page.

What's in the code:

  1. We receive the order amount
  2. Get 5% of the order amount
  3. Get the saved amount from the common metadata.
  4. Add to the saved amount 5% of the new order.
  5. Save the total amount in metadata.

My actual code:

// Get daily orders IDs to be checked
function get_order_ids_to_check(){
    global $wpdb;

    return $wpdb->get_col( "
        SELECT p.ID
        FROM {$wpdb->prefix}posts as p
        WHERE p.post_type LIKE 'shop_order'
        AND p.post_status IN ('wc-on-hold','wc-processing')
        AND UNIX_TIMESTAMP(p.post_date) >= (UNIX_TIMESTAMP(NOW()) - 86400)
    " );
}

function send_daily_orders_to_delivery() {

    // Loop through each order Ids
    foreach( get_order_ids_to_check() as $order_id ){
        // Get an instance of the WC_Order object
        $order  = wc_get_order($order_id);
        // Get order total
        $order_total = $order->get_total();
            $secret = ''; // Secret key to be set

        $data   = '&secret='.$secret.'&order_id='.get_post_meta( $order_id, 'delivery_order_id', true );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://app.example.com/api/index.php?get_status");
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);

        $decoded = (array) json_decode($result);

        // Update order status
        if( isset($decoded['result']) && $decoded['result'] == 'success' && isset($decoded['status']) && ! empty($decoded['status']) ){
            if( $decoded['status'] == "Completed" )
                $order->update_status( 'wc-completed' );
                // Get $update_total the total amount of percentages from metadata
                $saving_total = // Need code
                // Get 5 percent of the total order amount
                $percent = 5;
                $percent_total = ($percent / 100) * $order_total;
                // Get the sum of the numbers to update the value in the database
                $update_total = $saving_total + $percent_total; // This value must be overwritten in the database
                // Save $update_total the total amount of percentages to metadata (General metadata that can be called on any page created)
                update_post_meta(); // Need code
        }
    }
}

Upvotes: 2

Views: 250

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253869

As saving totals is a global dynamic unique value, it should be treat and saved as an option in wp_options Wordpress database table, using get_option() and update_option() related dedicated functions.

We will set this option value with autoload disabled, to avoid caching problems…

In your main function you should need to get this option value at start, then make your calculations on the value recursively for each order and then at the end update this value.

So for your main function, try something like:

function send_daily_orders_to_delivery() {
    // Get the actual option value for saving total orders amount
    $option_name = 'wc-orders-saving';
    $orders_saving = $new_orders_saving = (float) get_option( $option_name );
    $percent = 5; // saving percentage
    
    // Loop through each order Ids
    foreach( get_order_ids_to_check() as $order_id ){
        // Get an instance of the WC_Order object
        $order  = wc_get_order($order_id);
        // Get order total
        $order_total = $order->get_total();
            $secret = ''; // Secret key to be set

        $data   = '&secret='.$secret.'&order_id='.get_post_meta( $order_id, 'delivery_order_id', true );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://app.example.com/api/index.php?get_status");
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);

        $decoded = (array) json_decode($result);

        // If order is processable, add the calculation to saving total and update status
        if( isset($decoded['result']) && $decoded['result'] == 'success' && isset($decoded['status']) && ! empty($decoded['status']) &&$decoded['status'] == "Completed" ){
            // Set recursively calculation in existing "orders saving" value
            $new_orders_saving += (float) ($percent * $order_total / 100);
            
            // Update order status
            $order->update_status( 'wc-completed' );
        }
    }
    // Updating "Order saving" global value
    if( $orders_saving !== $new_orders_saving ) {
        if ( get_option( $option_name ) !== false ) {
            update_option($option_name, $new_orders_saving );
        } else {
            add_option( $option_name, $new_orders_saving, null, 'no' );
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). It should work.

If the option already exist, to avoid caching issue, you should need to delete it using:

delete_option('wc-orders-saving');

And adding it in your function.php file. Then browse any page of your web site and remove it.

Upvotes: 1

Related Questions