class WooCommerce_Printify_Sync { public static function sync_products_with_printify() { // Get Printify API key from options $printify_api_key = get_option('printify_api_key'); if (empty($printify_api_key)) { echo "Error: Printify API Key is not set."; return; } // Printify API URL to fetch products $url = 'https://api.printify.com/v1/products.json'; // Set up the request headers $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $printify_api_key, ), ); // Make the request using WP's HTTP API (wp_remote_get) $response = wp_remote_get($url, $args); // Debugging output: Check if there's an error in the API request if (is_wp_error($response)) { $error_message = $response->get_error_message(); error_log('Error fetching products from Printify: ' . $error_message); echo 'Error: ' . $error_message; return; } // Debugging: Check the response body $response_body = wp_remote_retrieve_body($response); error_log('Printify API Response: ' . $response_body); // Log the full response $data = json_decode($response_body, true); // Check if the response contains product data if (isset($data['data'])) { foreach ($data['data'] as $product) { self::create_woocommerce_product($product); } echo 'Products imported successfully!'; } else { error_log('No products found or error fetching products from Printify.'); echo 'No products found or error fetching products from Printify.'; } } // Example function to create WooCommerce products from Printify private static function create_woocommerce_product($product) { $post_data = array( 'post_title' => $product['title'], 'post_content' => $product['description'], 'post_status' => 'publish', 'post_type' => 'product', ); // Insert the product as a WooCommerce post $post_id = wp_insert_post($post_data); if ($post_id) { // Add WooCommerce specific data here (price, SKU, etc.) update_post_meta($post_id, '_price', $product['price']); update_post_meta($post_id, '_regular_price', $product['price']); update_post_meta($post_id, '_stock_status', 'instock'); } } }