首页 > 其他分享 >wordpress的火车头商品发布接口

wordpress的火车头商品发布接口

时间:2025-01-16 10:33:28浏览次数:3  
标签:火车头 set wc image product 接口 wordpress wp id

<?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);
}

请求数据如下:

            $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,
            ];

标签:火车头,set,wc,image,product,接口,wordpress,wp,id
From: https://blog.csdn.net/wangshifan116/article/details/145174123

相关文章

  • 接口漏洞扫描
    小程序漏洞扫描功能介绍一、小程序漏洞扫描功能简介为提高微信开放平台生态安全性,针对小程序开发过程中的安全问题,如敏感数据篡改、拖库信息泄露、WEB攻击等安全问题,平台向开发者提供漏洞扫描功能,协助开发者及运营者发现后台接口漏洞,并给出相应的修复指引。后续会进一步提供基......
  • Linux创建虚拟WLAN接口并测试
    Linux创建虚拟WLAN接口并测试|DD'NotesLinux创建虚拟WLAN接口并测试创建虚拟WLAN接口主要通过mac80211_hwsim内核模块实现,该模块可以模拟多个无线网卡设备,并支持创建虚拟的WLAN接口。mac80211_hwsim简介mac80211_hwsimisaLinuxkernelmodulethatcanbeusedtosimu......
  • 为WordPress网站设置第三方社交软件登录
    1.下载SuperSocializer外挂,为WordPress网站设置第三方社交软件登录由于wordpress配置的数据库是本地专用的,所以用户如果使用我们搭建的网站可能需要重新登陆,这无疑会是我们网站登录方面的痛点,所以使用第三方社交软件账号登录会很方便。2.使用域名登录网站昨天搭建网站的时候,使......
  • 接口性能优化技巧
    哪些问题会引起接口性能问题?这个问题的答案非常多,需要根据自己的业务场景具体分析。这里做一个不完全的总结:数据库慢查询深度分页问题未加索引索引失效join过多子查询过多in中的值太多单纯的数据量过大业务逻辑复杂循环调用顺序调用线......
  • 国产化板卡设计原理图:2136-KC705E增强版基于FMC接口的 JFM7K325T PCIeX8 接口卡
    KC705E增强版基于FMC接口的JFM7K325TPCIeX8接口卡    一、板卡概述   本板卡基于FPGAJFM7K325T 芯片,pin_to_pin兼容FPGAXC7K410T-2FFG900 ,支持PCIeX8、64bit DDR3容量2GByte,HPC的FMC连接器,板卡支持各种接口输入,软件支持windows,Linux驱动。    二、功......
  • 通用输入/输出接口(GPIO)入门指南:从原理到实践
    1GPIO基本概念与内部结构STM32的GPIO(通用输入输出端口)是最基本和常用的外设之一。每个GPIO端口包含16个可配置的I/O引脚,这些引脚可以独立编程为输入、输出或复用功能。每个引脚都可以配置为上拉、下拉或浮空状态,并且可以选择推挽或开漏输出模式。GPIO内部结构的核心组......
  • 国产化板卡设计原理图:基于FMC接口的JFM7K325T PCIeX4 3U PXIe接口卡
    一、板卡概述    本板卡基于FPGAJFM7K325T芯片,pin_to_pin兼容FPGAXC7K410T-2FFG900,支持PCIeX8、64bitDDR3容量2GByte,HPC的FMC连接器,板卡支持PXIE标准协议,其中XJ3标准高速差分接口,支持PCIeX2。软件具有windows,Linux驱动 二、功能和技术指标:四、应用领域  ......
  • 国产化FMC接口通用计算平台设计原理图:基于FMQL45T900 FMC接口通用计算平台
      一、板卡概述板卡由 FMQL45T900I芯片来完成卡主控及数字信号处理, FMQL45T900内部集成了两个ARMCortex-A9核和一个kintex7的FPGA,通过PL端FPGA扩展FMC、光纤、IO等接口,PS端ARM扩展网络、USB、RS232等接口。板卡适应于图像处理、震动、通信、雷达等前端信号处理或者手持机等......
  • 初阶数据结构【队列及其接口的实现】
    目录前言一、队列的概念及结构二、队列的实现方式三、队列的实现3.1基本结构3.2队列基本功能接口初始化队列销毁队列3.3入队列接口3.4出队列接口3.5队列的其它接口获取队列头部元素获取队列队尾元素检测队列是否为空获取队列中有效元素个数3.6测试总结前言......
  • Postman如何导出接口的几种方法?
    本文主要介绍了Postman如何导出接口的几种方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下前言:我的文章还是一贯的作风,简确用风格(简单确实有用),你们可叫我职场新人救星!好的废话不多说,今天这篇文章讲的是如何用postman导出接口文档!解决怎么把自......