前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >woocommerce通过代码添加商品之核心代码

woocommerce通过代码添加商品之核心代码

作者头像
IT不难
发布2023-11-17 13:52:22
2120
发布2023-11-17 13:52:22
举报
文章被收录于专栏:IT不难技术家园IT不难技术家园

前言

开发woocommerce批量发布商品插件的过程中,需要通过代码的形式将商品发布。分享用到的核心代码。包括商品创建、图片下载上传、变体商品添加。调试了好久,终于搞定。

lkt68ink.png
lkt68ink.png

核心代码

图片下载并上传媒体库

收到的产品链接,有时候不是标准链接,自己加上处理过程。

代码语言:javascript
复制
//图片处理函数
function download_and_import_imgs($img_arr) {
    $gallery_image_ids = [];

    //图片批量下载并导入
    foreach ($img_arr as $image_url) {
            //协议头处理
            if (!preg_match("~^(?:f|ht)tps?://~i", $image_url)) {
                    $image_url = 'https:' . $image_url;
            }

        //删掉?号后部分
                if (strpos($image_url, '?') !== false) {
                        $parsedUrl = parse_url($image_url);
                        $image_url = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path'];
                }

            // 下载图像并获取本地路径
            $temp_file = download_url($image_url);
            if (!is_wp_error($temp_file)) {
                    //文件名处理
                    $filename=basename($image_url);
                    $extension = pathinfo($filename, PATHINFO_EXTENSION);
                    if ($extension =='') {
                    $filename = $filename.'.jpg';
                    }

                    $file_array = array(
                            'name'     => $filename,
                            'tmp_name' => $temp_file
                    );

                    // 将图像添加到媒体库
                    $attachment_id = media_handle_sideload($file_array, 0);

                    if (!is_wp_error($attachment_id)) {
                            $gallery_image_ids[] = $attachment_id;
                    } else {
                            $err_msg = $temp_file->get_error_message();
                            error_log(__METHOD__ . PHP_EOL .print_r('添加媒体库:'.$err_msg, true));
                    }

            } else {
                    $err_msg = $temp_file->get_error_message();
                    error_log(__METHOD__ . PHP_EOL .print_r('下载图片:'.$err_msg, true));
            }
        }

    //返回
    return $gallery_image_ids;
}

创建产品

产品分为单体产品和变体产品

代码语言:javascript
复制
if (($_SERVER['REQUEST_METHOD'] === 'POST') && preg_match("/pimport/i", $_SERVER['REQUEST_URI'])) {
    // 获取 POST 请求的原始数据
    $postData = file_get_contents('php://input');

    // 解码 JSON 数据为关联数组
    $jsonData = json_decode($postData, true);

    //打印日志
    //error_log(__METHOD__ . PHP_EOL .print_r($jsonData, true));

    // 使用 isset() 函数检查是否存在特定的表单字段
    if (isset($jsonData['unique_id']) && isset($jsonData['mall_info'])) {
        $unique_id = $jsonData['unique_id'];
        $mall_info = $jsonData['mall_info'];

        // 进一步处理接收到的数据
    // 商品名称
    if (array_key_exists('name', $mall_info)) {
        $product_name = $mall_info['name'];
    } else {
        exit('fail');
    }

    // 获取商品sku信息
    if (array_key_exists('skus', $mall_info)) {
        $sku_arr=$mall_info['skus'];
        //多sku产品
    } else {
        $sku_arr = [];
    }

    switch (count($sku_arr)) {
        //未获取sku信息
        case 0:
            $product_type = 'simple';

            //自定义sku
            $sku = generate_random_sku();

            // price
            if (array_key_exists('price', $mall_info)) {
                $regular_price = $mall_info['price'];
                $sale_price = number_format($regular_price*0.9,2);

                // 商品状态
                        $status = 'publish';
            } else {
                $regular_price = 0;
                $sale_price = 0;

                // 商品状态
                        $status = 'draft';
            }

            if (array_key_exists('quantity', $mall_info)) {
                            $quantity = $mall_info['quantity'];
                    }else{
                            // 设置商品库存数量
                $quantity = rand(10,100);
                    }

            break;
        //单规格商品
        case 1:
            $product_type = 'simple';
            $sku = $sku_arr[0]['skuId'];

            if (array_key_exists('price', $sku_arr[0])) {
                $regular_price = $sku_arr[0]['price'];
                $sale_price = number_format($regular_price*0.9,2);

                // 商品状态
                                $status = 'publish';
            } else {
                $regular_price = 0;
                $sale_price = 0;

                // 商品状态
                        $status = 'draft';
            }

            if (array_key_exists('quantity', $sku_arr[0])) {
                            $quantity = $mall_info['quantity'];
                    }else{
                            // 设置商品库存数量
                $quantity = rand(10,100);
                    }

            break;
        //组合商品
        default:
            $product_type = 'variable';
            $sku = generate_random_sku();

                        if (array_key_exists('price', $sku_arr[0])) {
                                $regular_price = $sku_arr[0]['price'];
                                $sale_price = number_format($regular_price*0.9,2);

                                // 商品状态
                                $status = 'publish';
                        } else {
                                $regular_price = 0;
                                $sale_price = 0;

                                // 商品状态
                                $status = 'draft';
                        }

                        if (array_key_exists('quantity', $sku_arr[0])) {
                                $quantity = $sku_arr[0]['quantity'];
                        }else{
                                // 设置商品库存数量
                                $quantity = rand(10,100);
                        }
    }

    if ($product_type=='simple') {
        //创建产品
        $product = new WC_Product();
    }else{
        //创建产品
        $product = new WC_Product_Variable();
    }

    // 设置商品 SKU
    $product->set_sku($sku);

    // 设置名称
    $product->set_name($product_name);

    // 常规价格,促销价格
    $product->set_regular_price($regular_price);
    $product->set_sale_price($sale_price);

    // 库存
    $product->set_stock_quantity($quantity);


    // 产品相册
    if (array_key_exists('imgs', $mall_info)) {
        $image_ids=download_and_import_imgs($mall_info['imgs']);

        //图片大于0
        if (count($image_ids)>0) {
                // 设置商品图像
                $product->set_image_id($image_ids[0]);

            // 设置产品相册图像
                $product->set_gallery_image_ids($image_ids);
        } else {
            $stauts = 'draft';
        }
    }

    // 正文图片
    if (array_key_exists('descimgs', $mall_info)) {
        $descimgs = $mall_info['descimgs'];

        //下载图片并获取id列表
        $desc_image_ids=download_and_import_imgs($mall_info['descimgs']);
    }

    // 正文描述
    if (array_key_exists('desc', $mall_info)) {
        $description = $mall_info['desc'];

        //处理description

    } else {
        if (count($desc_image_ids)>0) {
            $description = '';

            foreach ($desc_image_ids as $image_id) {
                // 获取新上传图片的 URL
                        $new_image_url = wp_get_attachment_url($image_id);

                        // 将新图片的 HTML 标记添加到描述中
                        $new_image_html = '';
                        $description .= $new_image_html;
            }
        }else{
            $description = '';
        }
    }

    if(isset($description)) {
        // 设置更新后的描述
            $product->set_description($description);
    }

    // 设置产品分类
    $table_name = $wpdb->prefix . 'batch_upload_job';
    $query = $wpdb->prepare("SELECT category FROM $table_name WHERE unique_id = %s", $unique_id);
    $category = $wpdb->get_var($query);

    $category_ids = array($category,);
    $product->set_category_ids($category_ids);

    // 设置商品状态
        $product->set_status($status);

    // 创建
    $product_id = $product->save();

     // 多sku处理
        if ($product_type=='variable') {
            // 添加自定义属性
            $attribute_name = sanitize_title( 'pa_spec'.$product_id );
            $attribute_label = ucfirst( $attribute_name );

            if ( ! taxonomy_exists( $attribute_name ) ) {
                // 创建新属性
                $attribute_id = wc_create_attribute( array(
                    'name'         => $attribute_name,
                    'label'        => $attribute_label,
                    'slug'         => $attribute_name,
                    'type'         => 'select',
                    'order_by'     => 'menu_order',
                    'has_archives' => true
                ) );

                // 将属性关联到产品类型上
                register_taxonomy(
                    $attribute_name,
                    apply_filters( 'woocommerce_taxonomy_objects_' . $attribute_name, array( 'product' ) ),
                    apply_filters( 'woocommerce_taxonomy_args_' . $attribute_name, array(
                        'labels'       => array(),
                        'hierarchical' => false,
                        'show_ui'      => false,
                        'query_var'    => true,
                        'rewrite'      => false,
                    ) )
                );
            }
                foreach ( $sku_arr as $sku_info) {
                    create_product_variation($product_id, $sku_info);
                }

        // 获取所有可选项
            update_post_meta($product_id, '_product_attributes', array($attribute_name => array(
                'name'         => $attribute_name,
                'value'        => '',
                'position'     => 0,
                'is_visible'   => 1,
                'is_variation' => 1,
                'is_taxonomy'  => 1
            )));

            // 保存父产品
            $product->save();
        }

    #成功
    exit('success');
    } else {
    #失败
    exit('fail');
    }
}

变体产品创建函数

变体产品对应商品的不同规格,创建方法独立出来

代码语言:javascript
复制
//创建变体商品
function create_product_variation( $product_id, $variation_data ){
        $product = wc_get_product($product_id);
        $variation_post = array(
                'post_title'  => $product->get_title(),
                'post_name'   => $variation_data['skuName'],
                'post_status' => 'publish',
                'post_parent' => $product_id,
                'post_type'   => 'product_variation',
                'guid'        => $product->get_permalink()
        );
        $variation_id = wp_insert_post( $variation_post );
        $variation = new WC_Product_Variation( $variation_id );

        //规格属性
        $spec_taxonomy = sanitize_title( 'pa_spec'.$product_id );;
        $spec_term_name = $variation_data['skuName'];

        $post_spec_term_names =  wp_get_post_terms( $product_id, $spec_taxonomy, array('fields' => 'names') );

        if( ! in_array( $spec_term_name, $post_spec_term_names ) ){
                wp_set_post_terms( $product_id, $spec_term_name, $spec_taxonomy, true );
        }

        //将属性和产品关联
        $spec_term_slug = get_term_by('name', $spec_term_name, $spec_taxonomy )->slug;
        update_post_meta( $variation_id, 'attribute_'.$spec_taxonomy, $spec_term_slug );

        //sku
        if( ! empty( $variation_data['skuId'] ) )
                $variation->set_sku( $variation_data['skuId'].date('i:s') );

        //价格
        if( !empty( $variation_data['price'] ) ){
                $variation->set_regular_price($variation_data['price']);
                $variation->set_sale_price(number_format($variation_data['price']*0.9,2));
        } else {
                $variation->set_price(0);
                $variation->set_sale_price(0);
        }

        //库存
        if( ! empty( $variation_data['quantity'] ) ){
                $variation->set_stock_quantity( $variation_data['quantity'] );
                $variation->set_manage_stock( true );
                $variation->set_stock_status( '' );
        } else {
                $variation->set_manage_stock( false );
        }

        $variation->set_weight( '' );
        $variation->save();
}

完整插件

【效率插件】woocommerce之商品批量发布助手

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023年08月02日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 核心代码
    • 图片下载并上传媒体库
      • 创建产品
        • 变体产品创建函数
        • 完整插件
        相关产品与服务
        图片处理
        图片处理(Image Processing,IP)是由腾讯云数据万象提供的丰富的图片处理服务,广泛应用于腾讯内部各产品。支持对腾讯云对象存储 COS 或第三方源的图片进行处理,提供基础处理能力(图片裁剪、转格式、缩放、打水印等)、图片瘦身能力(Guetzli 压缩、AVIF 转码压缩)、盲水印版权保护能力,同时支持先进的图像 AI 功能(图像增强、图像标签、图像评分、图像修复、商品抠图等),满足多种业务场景下的图片处理需求。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档