/* * Plugin name: WooCommerce API Product Sync with Multiple Storess * Plugin URI: https://rudrastyh.com/woocommerce/product-sync-with-multiple-stores.html * Version: 1.0.0 * Author: Misha Rudrastyh */ class Misha_Sync_Woo_Products { public function __construct() { add_action( 'save_post_product', array( $this, 'sync' ), 99, 2 ); } public function sync( $product_id, $post ) { // do nothing if WooCommerce is not installed if( ! function_exists( 'wc_get_product' ) ) { return; } // get product object $product = wc_get_product( $product_id ); // do the sync for published products only if( 'publish' !== $product->get_status() ) { return; } // do the product sync with multiple WooCommerce stores from this array $stores = array( array( 'url' => 'https://miladnoorgold.ir', 'login' => 'ck_c0cf85d1da81550629b8c6fdbe12cda486a6f34a', // Consumer Key 'pwd' => 'cs_64082d38c0c27d84db0b7885dcbfcffa8d9df839', // Consumer Secret ), ); // prepare product data before the loop $product_data = $product->get_data(); // Fix: "Error 400. Bad Request. Cannot create existing product." unset( $product_data[ 'id' ] ); // Fix: "Error 400 Bad Request low_stock_amount is not of type integer,null." error $product_data[ 'low_stock_amount' ] = (int) $product_data[ 'low_stock_amount' ]; // In order to sync a product image we have to do some additional stuff if( $product_data[ 'image_id' ] ) { $product_data[ 'images' ] = array( array( 'src' => wp_get_attachment_url( $product_data[ 'image_id' ] ) ) ); unset( $product_data[ 'image_id' ] ); } // let's loop through multiple stores and sync the product with each of them foreach( $stores as $store ) { $endpoint = "{$store[ 'url' ]}/wp-json/wc/v3/products"; $method = 'POST'; // let's check if the product with the same SKU already exists if( $product_id_2 = $this->product_exists( $product, $store ) ) { $endpoint = "{$endpoint}/{$product_id_2}"; $method = 'PUT'; } // WooCommerce API product sync request wp_remote_request( $endpoint, array( 'method' => $method, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( "{$store[ 'login' ]}:{$store[ 'pwd' ]}" ) ), 'body' => $product_data ) ); } } private function product_exists( $product, $store ) { $sku = $product->get_sku(); $request = wp_remote_get( add_query_arg( 'sku', $sku, "{$store[ 'url' ]}/wp-json/wc/v3/products" ), array( 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( "{$store[ 'login' ]}:{$store[ 'pwd' ]}" ) ) ) ); if( 'OK' === wp_remote_retrieve_response_message( $request ) ) { $products = json_decode( wp_remote_retrieve_body( $request ) ); if( $products ) { $product = reset( $products ); return $product->id; } } return false; } } new Misha_Sync_Woo_Products;