wordpress的火车头商品发布接口

php 复制代码
<?php
require '../wp-load.php';
ini_set('memory_limit', '1024M');
set_time_limit(180);

$top_cat = '';
# 图片链接域名替换
$image_host = '';

$start_time = microtime(true);

$counter = 0;
// 临时缓存
$products = $skus = $categories = [];
$var_sku_index = 1;

$rowData=$_POST;

// if ($_SERVER['HTTP_HOST'] == 'www.solglasogononline.com') {
// //   logArray($rowData);
  
// }


$attrs=explode('|',$rowData['wp_attname']);
$result=[];

if($rowData['wp_attvalue']){
    // 如果属性大于1
    if (count($attrs) > 1) {
        $parts = explode('|', $rowData['wp_attvalue']);
        $result = array_map(function ($part) {
            return explode("___", $part);
        }, $parts);
    } else {
        if (strpos($rowData['wp_attvalue'], "___") !== false) {
            $result[0] = explode("___", $rowData['wp_attvalue']);
        } else {
            $result[0] = explode("|", $rowData['wp_attvalue']);
        }
    }
}

while (count($attrs) < 3) {
    $attrs[] = '';
}

while (count($result) < 3) {
    $result[] = '';
}

// 产品细节图
$wpImgs= explode("|", trim($rowData['wp_img']));
if (strpos($rowData['wp_img'], "\n") !== false) {
    $wpImgs= explode("\n", trim($rowData['wp_img']));
}
// 产品细节图如果大于5张只取5张
if (count($wpImgs) > 5) {
    $wpImgs = array_slice($wpImgs, 0, 5);
}

// 产品主图
$mainImage= isset($rowData['mainimg']) ? $rowData['mainimg'] : $rowData['minimg'];
if (empty($mainImage) && count($wpImgs) > 0) {
    $mainImage = trim($wpImgs[0]); 
}

// 原价 // 销售价
$rowData['wp_price'] = convertToNumber($rowData['wp_price']);
$rowData['wp_saleprice'] = convertToNumber($rowData['wp_saleprice']);
$regularPrice = $rowData['wp_price']>0?(float) $rowData['wp_price']:(float) $rowData['wp_saleprice'];
$salePrice = $rowData['wp_saleprice']?(float) $rowData['wp_saleprice']:(float) $rowData['wp_price'];

// 目录
$rowData['wp_categories'] = str_replace('Home|','',trim($rowData['wp_categories']));
$rowData['wp_categories'] = str_replace("\'"," ",trim($rowData['wp_categories']));

$productData = [
    'sku' => trim($rowData['wp_sku']),
    'title' => trim($rowData['wp_title']),
    'description' => trim($rowData['wp_description']),

    'option1' => trim($attrs[0]),
    'option1_value' => $result[0],
    'option2' => trim($attrs[1]),
    'option2_value' => $result[1],
    'option3' => trim($attrs[2]),
    'option3_value' => $result[2],

    'regular_price' => $regularPrice,
    'sale_price' => $salePrice,
    'images' => $wpImgs,
    'main_image' => $mainImage,
    'categories' => str_replace('|','>',$rowData['wp_categories']),
    // 'image_id' => 0,
    // 'image_ids' => [],
    // 'category_ids' => [],
    'options' => [],
];

// var_dump($productData);exit;

// 检查是否有效
if (! empty($productData['sku']) && ! empty($productData['regular_price']) && ! empty($productData['main_image'])) {
    // 搜索SKU产品是否存在 存在则跳过
    $find = wc_get_product_id_by_sku($productData['sku']);

    if ($find) {
        echo "error 产品已存在";
        die;
    }

    // 替换图片域名
    if (! empty($image_host)) {
        $productData['main_image'] = preg_replace('/^(https?\:\/\/)[^\/]+(.*)/si', "$1{$image_host}$2", $productData['main_image']);
    }

    // 主产品还是变体
    if (! isset($products[$productData['sku']])) {
        // 主产品
        if (empty($productData['title']) || empty($productData['categories'])) {
            echo "error 标题与分类均不能为空";
            die;
        }
        // 创建产品
        // 检查价格
        if ($productData['regular_price'] <= 0 || $productData['sale_price'] <= 0) {
            echo "error 价格异常";
            die;
        }

        $products[$productData['sku']] = $productData;
    }

    // 扫描属性
    $options = [
        'option1' => $productData['option1_value'],
        'option2' => $productData['option2_value'],
        'option3' => $productData['option3_value'],
        'regular_price' => $productData['regular_price'],
        'sale_price' => $productData['sale_price'],
        'image' => $productData['main_image'],
    ];

    $products[$productData['sku']]['options'][] = $options;
} else {
    echo "error 无效的产品数据,SKU、原价与主图均不能为空";
    die;
}

$product_count = count($products);

foreach ($products as $sku => $myProduct) {
    $counter++;
    $var_sku_index = 1;
    $Option1_data = [];
    $Option2_data = [];
    $Option3_data = [];

    foreach ($myProduct['options'] as $ops){
        if ($ops['option1']){
            $Option1_data = $ops['option1'];
        }

    }
    foreach ($myProduct['options'] as $ops){
        if ($ops['option2']){
            $Option2_data = $ops['option2'];
        }
    }
    foreach ($myProduct['options'] as $ops){
        if ($ops['option3']){
            $Option3_data = $ops['option3'];
        }
    }

    // 创建主图
    $image_id = image_link_upload($myProduct['main_image']);

    // 检查主图是否导入成功
    if (! is_numeric($image_id) || $image_id <= 0) {
        echo "error 主图导入失败";
        die;
    }

    $image_ids = [];
    foreach ($myProduct['images'] as $image) {
        $img_id = image_link_upload($image);

        if (is_numeric($img_id) && $img_id > 0) {
            $image_ids[] = $img_id;
        }
    }

    // 创建类目
    $category_ids = [];
    $md5 = md5($myProduct['categories']);

    if (isset($categories[$md5])) {
        $category_ids = $categories[$md5];
    } else {
        $category_ids = create_categories($myProduct['categories']);
        $categories[$md5] = $category_ids;
    }

    if (empty($category_ids)) {
        echo "error 类目导入失败";
        die;
    }
    
    if (! empty($Option1_data)) {
        $wc_product = new WC_Product_Variable();
        $wc_product->set_name($myProduct['title']);
        $wc_product->set_regular_price($myProduct['regular_price']);
        $wc_product->set_sale_price($myProduct['sale_price']);
        $wc_product->set_description($myProduct['description']);
        $wc_product->set_sku($myProduct['sku']);
        $wc_product->set_catalog_visibility('visible');
        $wc_product->set_manage_stock(true);
        $wc_product->set_stock_status('instock');
        $wc_product->set_stock_quantity(9999);
        $wc_product->set_status('publish');
        $wc_product->set_tax_status('none');
        $wc_product->set_tax_class('zero-rate');
        $wc_product->set_image_id($image_id);
    }else{
        $wc_product = new WC_Product_Simple();
        $wc_product->set_name($myProduct['title']);
        $wc_product->set_regular_price($myProduct['regular_price']);
        $wc_product->set_sale_price($myProduct['sale_price']);
        $wc_product->set_description($myProduct['description']);
        $wc_product->set_sku($myProduct['sku']);
        $wc_product->set_catalog_visibility('visible');
        $wc_product->set_manage_stock(true);
        $wc_product->set_stock_status('instock');
        $wc_product->set_stock_quantity(9999);
        $wc_product->set_status('publish');
        $wc_product->set_tax_status('none');
        $wc_product->set_tax_class('zero-rate');
        $wc_product->set_image_id($image_id);
    }

    if (! empty($image_ids)) {
        $wc_product->set_gallery_image_ids( $image_ids );
    }

    $wc_product->set_category_ids( $category_ids );

    // 属性
    $attribute_data = [];

    if (! empty($Option1_data)) {
        $attribute = new WC_Product_Attribute();
        $attribute->set_name( $myProduct['option1'] );
        $attribute->set_options( array_values(array_unique($Option1_data)) );
        $attribute->set_position( 0 );
        $attribute->set_visible( true );
        $attribute->set_variation( true );
        $attribute_data[] = $attribute;
    }
    if (! empty($Option2_data)) {
        $attribute = new WC_Product_Attribute();
        $attribute->set_name( $myProduct['option2'] );
        $attribute->set_options( array_values(array_unique($Option2_data)) );
        $attribute->set_position( 0 );
        $attribute->set_visible( true );
        $attribute->set_variation( true );
        $attribute_data[] = $attribute;
    }
    if (! empty($Option3_data)) {
        $attribute = new WC_Product_Attribute();
        $attribute->set_name( $myProduct['option3'] );
        $attribute->set_options( array_values(array_unique($Option3_data)) );
        $attribute->set_position( 0 );
        $attribute->set_visible( true );
        $attribute->set_variation( true );
        $attribute_data[] = $attribute;
    }

    if (! empty($attribute_data)) {
        $wc_product->set_attributes( $attribute_data );
    }

    $wc_product->save();
    // $wc_product->check_stock();
    $main_product_id = $wc_product->get_id();

    

    if (! empty($Option1_data)) {
        foreach ($myProduct['options'] as $ops) {
            $ops_data = [];
            if ($Option1_data) {
                $ops_data[] = $ops['option1'];
            }
            if ($Option2_data) {
                $ops_data[] = $ops['option2'];
            }
            if ($Option3_data) {
                $ops_data[] = $ops['option3'];
            }
            
            # 变体图片上传
            // $var_image_id = image_link_upload($ops['image']);
            // TODO::暂时直接使用SKU图片
            $var_image_id = $image_id;


            if (is_numeric($var_image_id) && $var_image_id > 0) {
                $var_sku = "{$sku}_{$var_sku_index}";

                $variation = new WC_Product_Variation();
                $variation->set_parent_id($main_product_id);
                $variation->set_attributes($ops_data[0]);
                $variation->set_regular_price($ops['regular_price']);
                $variation->set_sale_price($ops['sale_price']);
                $variation->set_image_id($var_image_id);
                $variation->set_manage_stock(true);
                $variation->set_status('publish');
                $variation->set_stock_status('instock');
                $variation->set_stock_quantity(9999);
                $variation->set_downloadable(false);
                $variation->set_virtual(false);
                $variation->set_sku($var_sku);
                $variation->save();


                $var_sku_index++;
            } else {

            }
        }
    }
    echo "success 主产品导入成功";
    die;
}

// 图片上传程序
function image_link_upload($image_url){

    $url = trim($image_url);
    $check_filetype = wp_check_filetype( basename( $url ), null );

    $attachment_image = array(
        'post_title'     => apply_filters('exmage_insert_attachment_image_name', "", "", $url, 0),
        'post_mime_type' => empty( $check_filetype['type'] ) ? 'image/url' : $check_filetype['type'],
        'guid'           => strlen( $url ) > 255 ? '' : $url,//guid is varchar(255)
        'post_status'    => 'inherit',
        'file' => $url,
    );

    // 手动插入图片附件 for EXMAGE_WP_IMAGE_LINKS 站外图片链接
    $attachment_id = wp_insert_attachment( $attachment_image, $url, 0, true );
    if ($attachment_id && !is_wp_error( $attachment_id )) {
        update_post_meta( $attachment_id, '_exmage_external_url', $url );
        return $attachment_id;
    } else {
        return $attachment_id->get_error_message();
    }


    // $image_id = "";
    // $post_parent = "0";

    // if(class_exists( 'EXMAGE_WP_IMAGE_LINKS' )){
    //     if (preg_match('/^https?\:\/\//si', $image_url)) {
    //         $add_image = EXMAGE_WP_IMAGE_LINKS::add_image( $image_url, $image_id, $post_parent );
    //         if ($add_image["id"]){
    //             return (int) $add_image["id"];
    //         } else {
    //             return $add_image["message"];
    //         }
    //     } else {
    //         return "error 无效的图片链接 ---> $image_url";
    //     }
    // } else {
    //     echo "error 请先安装 EXMAGE_WP_IMAGE_LINKS 插件!\n";
    //     die;
    // }
}

function create_categories($categories = '') {
    global $top_cat;

    $categories = trim($categories);

    if (! empty($categories)) {
        if (! empty($top_cat)) {
            $categories = "{$top_cat}>{$categories}";
        }
    }
    $categories_str = $categories;
    $categories = explode('>', trim($categories));

    $id_array = [];
    $parent_id = 0;

    foreach ($categories as $category_name) {
        $category_name = strtolower(trim($category_name));

        if (empty($category_name)) {
            continue;
        }

        $args = array(
            'taxonomy'   => 'product_cat',
            'parent'     => $parent_id,
            'hide_empty' => false,
        );
        
        $terms = get_terms($args);
        
        $categoryNname = htmlentities($category_name, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $categoryNname2 = str_replace('&amp;', '&', $category_name);
        $categoryNname2 = str_replace('&', '&amp;', $categoryNname2);

        // 检查是否有匹配名称的类目
        $found_term = false;
        if (!empty($terms) && !is_wp_error($terms)) {
            foreach ($terms as $term) {
                // if ($_SERVER['HTTP_HOST'] == 'www.solglasogononline.com') {
                //     var_dump($term->name .'----'. $category_name .'----'.  $categoryNname .'----'.$categoryNname2);
                // }
                $_name = strtolower($term->name);
                
                if ($_name === $category_name || $_name === $categoryNname || $_name === $categoryNname2) {
                    $found_term = $term;
                    break;
                }
            }
        }
        
        // if ($_SERVER['HTTP_HOST'] == 'www.solglasogononline.com') {
        //             var_dump($category_name . '===' . !$found_term);
        //         }

        if ($found_term) {
            $id_array[] = $found_term->term_id;
            $parent_id = $found_term->term_id;
        } else {
            // 创建类目
            $new_term = wp_insert_term($category_name, 'product_cat', array('parent' => $parent_id));

            if (!is_wp_error($new_term)) {
                $id_array[] = $new_term['term_id'];
                $parent_id = $new_term['term_id'];
            } else {
                // 类目创建失败,打印错误信息
                echo "-> 错误:类目 {$categories_str}.{$category_name} 创建失败 ---> " . $new_term->get_error_message() . "\n";
                die;
            }

        }
    }

    return $id_array;
}

function convertToNumber($str) {
    preg_match('/[\d.]+/', $str, $matches);
    if (!empty($matches)) {
        return floatval($matches[0]);
    }
    return 0;
}

function logArray($array) {
    $logFile = 'logs.txt'; // 日志文件名
    $timestamp = date('Y-m-d H:i:s'); // 时间戳格式

    // 格式化数组内容
    $logEntry = "[" . $timestamp . "] " . print_r($array, true) . PHP_EOL;

    // 写入日志文件
    file_put_contents($logFile, $logEntry, FILE_APPEND);
}

请求数据如下:

php 复制代码
            $rowData = [
                'wp_title' => 'Dog leash Pony makarony Ginger',
                'minimg' => 'https://s3.lax.sharktech.net/img/2121-sn3o3g3u3kw51.jpg',
                'wp_img' => 'https://s3.lax.sharktech.net/img/2121-sn3o3g3u3kw51.jpg|https://s3.lax.sharktech.net/img/2122-itlbf1neu3c52.jpg|https://s3.lax.sharktech.net/img/2123-vqtkibfgxcd53.jpg|https://s3.lax.sharktech.net/img/2125-tnmhvdt1aeh54.jpg|https://s3.lax.sharktech.net/img/2127-onkjwwocpuq55.jpg',
                'wp_attname' => 'Size',
                'wp_attname' => 'Color|Style',
                //'wp_attvalue' => '140 cm|170 cm',
                'wp_attvalue' => 'Pink___Camel___Beige|M___L___XL',
                'wp_description' => '<p>Is your dog fidgety and unrestrained and no leash can hold it? Our Pony-Makarony is created<span class="Apple-converted-space"> </span>specifically for the most active ones.<span class="Apple-converted-space"> </span></p>
 <p>Standard thick rope 11 mm fits for medium and large sized dogs.</p>
 <p>Thin rope 7 mm and lightweight hardware available for small dogs under 5 kg.<span class="Apple-converted-space"> </span></p>
 <p>- genuine Italian leather</p>
 <p>- bronze cast hardware</p>
 <p>- polyamid rope</p>
 <p>- Handmade</p>
 <p>- our love</p>
 <p>Harness is included in the photos as an illustration of how a set might be assembled and is ordered separately.<span class="Apple-converted-space"> </span></p>',
                'wp_price' => '',
                'wp_categories' => 'Dog leash & collar',
                'wp_saleprice' => '$59',
                'wp_sku' => 'H4kXL0',
                'cat_id'=>25,
            ];
相关推荐
請叫我菜鳥2 小时前
PHP xml 常用函数整理
开发语言·php
Andya_net8 小时前
计算机网络 | 什么是公网、私网、NAT?
开发语言·计算机网络·php
网络安全Max10 小时前
网络安全概论——网络安全基础
网络·web安全·php
小彭爱学习14 小时前
php审计1-extract函数变量覆盖
web安全·网络安全·php·ctf·代码审计·extract
Andya_net1 天前
网络安全 | 什么是正向代理和反向代理?
安全·web安全·php
寰宇软件1 天前
PHP智慧小区物业管理小程序
小程序·uni-app·vue·php
万亿少女的梦1681 天前
基于php求职招聘系统设计
android·php·求职招聘
昵称难产中1 天前
浅谈云计算13 | 网络虚拟化
网络·云计算·php