在 WooCommerce 中以编程方式创建可变产品和两个新属性

2023-11-23

我想以编程方式创建一个具有两个新变量属性的变量产品(“父”产品) - 所有这些属性都来自 WordPress 插件(因此没有对 API 的 HTTP 请求)。

这两个变量属性也应该动态创建。

如何才能做到这一点 ?

(使用 WooCommerce 版本 3)


更新:我已经编写了更多我希望的代码行,并尝试了很多方法来解决它,使用 wooCommerce 对象,并使用 WordPress 数据库在数据库中添加了有关术语、termmeta、术语与帖子的关系的缺失数据对象 - 但没有什么足以让它发挥作用。而且我无法指出我错在哪里 - 这就是为什么我无法提供更窄的问题 - stackoverflow 更适合的事情。


After: 以编程方式创建具有新属性值的 WooCommerce 产品变体

在这里,您可以使用新的产品属性+值创建新的可变产品:

/**
 * Save a new product attribute from his name (slug).
 *
 * @since 3.0.0
 * @param string $name  | The product attribute name (slug).
 * @param string $label | The product attribute label (name).
 */
function save_product_attribute_from_name( $name, $label='', $set=true ){
    if( ! function_exists ('get_attribute_id_from_name') ) return;

    global $wpdb;

    $label = $label == '' ? ucfirst($name) : $label;
    $attribute_id = get_attribute_id_from_name( $name );

    if( empty($attribute_id) ){
        $attribute_id = NULL;
    } else {
        $set = false;
    }
    $args = array(
        'attribute_id'      => $attribute_id,
        'attribute_name'    => $name,
        'attribute_label'   => $label,
        'attribute_type'    => 'select',
        'attribute_orderby' => 'menu_order',
        'attribute_public'  => 0,
    );


    if( empty($attribute_id) ) {
        $wpdb->insert(  "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
        set_transient( 'wc_attribute_taxonomies', false );
    }

    if( $set ){
        $attributes = wc_get_attribute_taxonomies();
        $args['attribute_id'] = get_attribute_id_from_name( $name );
        $attributes[] = (object) $args;
        //print_r($attributes);
        set_transient( 'wc_attribute_taxonomies', $attributes );
    } else {
        return;
    }
}

/**
 * Get the product attribute ID from the name.
 *
 * @since 3.0.0
 * @param string $name | The name (slug).
 */
function get_attribute_id_from_name( $name ){
    global $wpdb;
    $attribute_id = $wpdb->get_col("SELECT attribute_id
    FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
    WHERE attribute_name LIKE '$name'");
    return reset($attribute_id);
}

/**
 * Create a new variable product (with new attributes if they are).
 * (Needed functions:
 *
 * @since 3.0.0
 * @param array $data | The data to insert in the product.
 */

function create_product_variation( $data ){
    if( ! function_exists ('save_product_attribute_from_name') ) return;

    $postname = sanitize_title( $data['title'] );
    $author = empty( $data['author'] ) ? '1' : $data['author'];

    $post_data = array(
        'post_author'   => $author,
        'post_name'     => $postname,
        'post_title'    => $data['title'],
        'post_content'  => $data['content'],
        'post_excerpt'  => $data['excerpt'],
        'post_status'   => 'publish',
        'ping_status'   => 'closed',
        'post_type'     => 'product',
        'guid'          => home_url( '/product/'.$postname.'/' ),
    );

    // Creating the product (post data)
    $product_id = wp_insert_post( $post_data );

    // Get an instance of the WC_Product_Variable object and save it
    $product = new WC_Product_Variable( $product_id );
    $product->save();

    ## ---------------------- Other optional data  ---------------------- ##
    ##     (see WC_Product and WC_Product_Variable setters methods)

    // THE PRICES (No prices yet as we need to create product variations)

    // IMAGES GALLERY
    if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
        $product->set_gallery_image_ids( $data['gallery_ids'] );

    // SKU
    if( ! empty( $data['sku'] ) )
        $product->set_sku( $data['sku'] );

    // STOCK (stock will be managed in variations)
    $product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
    $product->set_manage_stock(true);
    $product->set_stock_status('');

    // Tax class
    if( empty( $data['tax_class'] ) )
        $product->set_tax_class( $data['tax_class'] );

    // WEIGHT
    if( ! empty($data['weight']) )
        $product->set_weight(''); // weight (reseting)
    else
        $product->set_weight($data['weight']);

    $product->validate_props(); // Check validation

    ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##

    $product_attributes = array();

    foreach( $data['attributes'] as $key => $terms ){
        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
        $attr_label = ucfirst($key); // attribute label name
        $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug

        // NEW Attributes: Register and save them
        if( ! taxonomy_exists( $taxonomy ) )
            save_product_attribute_from_name( $attr_name, $attr_label );

        $product_attributes[$taxonomy] = array (
            'name'         => $taxonomy,
            'value'        => '',
            'position'     => '',
            'is_visible'   => 0,
            'is_variation' => 1,
            'is_taxonomy'  => 1
        );

        foreach( $terms as $value ){
            $term_name = ucfirst($value);
            $term_slug = sanitize_title($value);

            // Check if the Term name exist and if not we create it.
            if( ! term_exists( $value, $taxonomy ) )
                wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term

            // Set attribute values
            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
        }
    }
    update_post_meta( $product_id, '_product_attributes', $product_attributes );
    $product->save(); // Save the data
}

代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。


USAGE(具有 2 个新属性 + 值的示例):

create_product_variation( array(
    'author'        => '', // optional
    'title'         => 'Woo special one',
    'content'       => '<p>This is the product content <br>A very nice product, soft and clear…<p>',
    'excerpt'       => 'The product short description…',
    'regular_price' => '16', // product regular price
    'sale_price'    => '', // product sale price (optional)
    'stock'         => '10', // Set a minimal stock quantity
    'image_id'      => '', // optional
    'gallery_ids'   => array(), // optional
    'sku'           => '', // optional
    'tax_class'     => '', // optional
    'weight'        => '', // optional
    // For NEW attributes/values use NAMES (not slugs)
    'attributes'    => array(
        'Attribute 1'   =>  array( 'Value 1', 'Value 2' ),
        'Attribute 2'   =>  array( 'Value 1', 'Value 2', 'Value 3' ),
    ),
) );

经过测试并有效。


有关的:

  • 在 Woocommerce 中以编程方式创建新产品属性
  • 以编程方式创建具有新属性值的 WooCommerce 产品变体
  • 在 Woocommerce 3 中使用 CRUD 方法以编程方式创建产品
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 WooCommerce 中以编程方式创建可变产品和两个新属性 的相关文章

  • PHP 的password_verify() 是否可以抵御极长的密码(DoS 攻击)?

    一般攻击场景 2013 年 Django 存在一个普遍漏洞 攻击者可以通过非常大的密码创建极其密集的 CPU 计算 请参阅此处的安全通知 https www djangoproject com weblog 2013 sep 15 secu
  • PHP 异常处理与 C#

    这是一个非常基本的问题 我希望如此 我所做的大部分异常处理都是使用 C 进行的 在 C 中 任何在 try catch 块中出错的代码都会由 catch 代码处理 例如 try int divByZero 45 0 catch Except
  • Codeigniter PHP - 在锚点加载视图

    我在一个长页面的底部有一个表单 如果用户填写了表单但它不验证页面是否以典型的 codeigniter 方式重新加载 this gt load gt view template data 然而 由于表单位于页面底部 我需要将页面加载到那里 就
  • Symfony2,如何向表单添加隐藏的日期类型字段?

    我正在尝试以下场景 In myclassType public function buildForm FormBuilder builder array options builder gt add day hidden gt add da
  • 用 PHP 截断文件末尾

    我有一个日志文件 我想在 PHP 读取该文件后将其截断 我的代码目前如下所示 fp fopen file r ftruncate fp 125000 fclose fp 但是 这会通过保留first1MB 不过 我想保留last1Mb 的文
  • Laravel 5.4 将json保存到数据库

    帮我将 json 保存到数据库 表字段类型 文本 我有带有强制转换数组的模型 class Salesteam extends Model protected casts team members gt array 我想要像这样 index
  • 在 CodeIgniter 中添加新页面

    对于我对 CodeIgniter 和 MVC 系统的无知 我提前表示歉意 我正在帮助一位家庭成员处理他们的商业网站 到目前为止 我已经能够仅通过逻辑来完成大部分所需的更改 但现在我已经走进了死胡同 我不打算继续支持他们 因为我显然不是 Co
  • zend 表单验证

    我想知道 Zend Form 如何验证输入 我的意思是它如何知道要验证哪些输入字段 我查看了 php 全局变量 POST GET 但没有看到任何设置为标识符 例如 的内容 以便了解如何验证 有人能给我推荐一些关于这些东西的指南吗 好吧 找出
  • 使用 PHP 更新 XML 节点

    我有一个 XML 文件 test xml
  • 随机错误 symfony:ContextErrorException: 警告: simplexml_load_file(): I/O 警告: 无法加载外部实体

    在我的 Symfony 项目中 当我进入应用程序中的随机页面时 会出现以下随机错误 ContextErrorException Warning simplexml load file I O warning failed to load e
  • 查明具有特定 ID 的会话是否已过期

    我正在创建一个上传功能 将用户上传的文件存储在服务器上 并以用户的会话 ID 作为名称 现在 我只想将此文件保留在服务器上 直到该会话处于活动状态 所以 我的问题是 如何根据会话 ID 确定会话是活动的还是过期的 以便在后一种情况下我可以安
  • PHP 中的静态类初始值设定项

    我有一个带有一些静态函数的辅助类 类中的所有函数都需要一个 重 初始化函数来运行一次 就好像它是一个构造函数 有实现这一目标的良好实践吗 我唯一想到的就是打电话init函数 如果它已经运行过一次 使用静态 initialized变种 问题是
  • Zend RegEx Validator 的自定义有意义的错误消息

    我正在验证表单中的文本字段 如下所示 name new Zend Form Element Text name name gt setLabel First Name gt setRequired true gt addFilter new
  • 在 PHP 中将整数转换为十六进制值

    如何将PHP中第一类中的数字转换为第二类中的数字 是否有内置函数来转换数字 也是我的标题 将整数转换为十六进制值 甚至正确 class Permission const READ 1 const UPDATE 2 const DELETE
  • 当路由不存在时重定向 laravel 4

    我正在使用 laravel 4 当我的项目处于生产模式时 我得到 抱歉 找不到您要查找的页面 当我到达一条不存在的路线时 当我 grep 我的代码时 它在两个地方找到 vendor symfony debug Symfony Compone
  • 细胞的 fpdf 对齐

    我正在尝试使用生成 PDFfpdf我有一个小问题 我需要有 2 个单元格 如下所示 Address Line 1 Version Address Line 2 1 0 City 06 05 2011 我尝试过使用MultiCell 但没有运
  • 从检查元素隐藏 ''

    我有这个 HTML 和 PHP 联系表
  • 使用 Swift 邮件程序发送邮件时出现错误 501

  • Google Drive 服务帐户上传的位置

    我正在尝试使用服务帐户将文件上传到我的 Google 云端硬盘 当我部署此代码时 我不希望用户给予授权 我希望他们上传到我的帐户 我通过 PHP 使用它 下面是我到目前为止的情况 这段代码是基于官方文档给出的例子 当我运行 php 脚本时
  • 如何统计订单总价?

    我有这些表 Orders id status user id address id 1 await 1 1 products id name price quantity 1 test1 100 5 2 test2 50 5 order p

随机推荐