Custom Cron Schedules on a Plugin
- سُلَيْمَان بْن دَاوُوْد

- Jun 5, 2020
- 1 min read
<?php/*Plugin Name: Mustek WooCommerce Stock UpdaterPlugin URI : https://api.mustek.co.zaDescription: This plugin is used to update stocks for products.*/register_activation_hook( __FILE__, 'call_mustek_stock_updater_init' );function call_mustek_stock_updater_init() { if ( ! wp_next_scheduled( 'call_mustek_stock_updater' ) ) { wp_schedule_event( time(), 'minutely', 'call_mustek_stock_updater' ); }}/*Filter to add custom Time in Seconds to cron scedule array*/add_filter( 'cron_schedules', 'custom_five_minute_schedule' ); function custom_five_minute_schedule( $schedules ) { $schedules['minutely'] = array( 'interval' => 300, //7 days * 24 hours * 60 minutes * 60 seconds[7 * 24 * 60 * 60,] 'display' => __( '5 Minutely', 'text-domain' ) ); return $schedules;}add_action( 'call_mustek_stock_updater', 'call_mustek_stock_updater_callback' );function call_mustek_stock_updater_callback(){ $url = "https://api.mustek.co.za/Customer/ItemsStock.ashx?CustomerToken=8C6381DB-D817-A319"; $csvData = file_get_contents($url); $lines = explode(PHP_EOL, $csvData); $array = array(); foreach ($lines as $line) { $array[] = str_getcsv($line); } $i = 0; foreach ($array as $items) { if($i != 0){ /* print_r($items);*/ $product = get_mustek_product_by_sku( $items[0] ); if(is_object($product)){ $quantity = $product->get_stock_quantity('view'); $newstock = $items[2]; if((int) $quantity != (int) $newstock ) { wc_update_product_stock($product, $newstock); } } } $i++; }}/*Helper Function to get Product by SKU*/function get_mustek_product_by_sku( $sku ) { global $wpdb; $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='wpcf-mustek_sku' AND meta_value='%s' LIMIT 1", $sku ) ); if ( $product_id ) return wc_get_product( $product_id ); return null;}
Comments