Wordpress Woocommerce - 使用 update_post_meta 添加产品属性 [英] Wordpress Woocommerce - use update_post_meta to add product attributes

查看:40
本文介绍了Wordpress Woocommerce - 使用 update_post_meta 添加产品属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我客户网站中的产品需要某些属性,我已通过 产品 -> 属性 在 Wordpress 管理中添加了这些属性.在我编写的这个导入脚本中,我需要使用函数 update_post_meta($post_id, $meta_key, $meta_value) 来导入正确的属性和值.

The products in my clients website require certain attributes which I have added via Products -> Attributes in the Wordpress administration. In this import script I'm coding I need to use the function update_post_meta($post_id, $meta_key, $meta_value) to import the proper attributes and values.

目前我有这样的功能:

update_post_meta( $post_id, '_product_attributes', array());

但是我不确定如何正确传递属性及其值?

However I'm not sure how to properly pass along the attributes and their values?

推荐答案

是的,所以我自己花了一段时间才弄明白,但我终于通过编写以下函数设法做到了:

Right so it took me a while to figure it out myself but I finally managed to do this by writing the following function:

// @param int $post_id - The id of the post that you are setting the attributes for
// @param array[] $attributes - This needs to be an array containing ALL your attributes so it can insert them in one go
function wcproduct_set_attributes($post_id, $attributes) {
    $i = 0;
    // Loop through the attributes array
    foreach ($attributes as $name => $value) {
        $product_attributes[$i] = array (
            'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name
            'value' => $value, // set attribute value
            'position' => 1,
            'is_visible' => 1,
            'is_variation' => 1,
            'is_taxonomy' => 0
        );

        $i++;
    }

    // Now update the post with its new attributes
    update_post_meta($post_id, '_product_attributes', $product_attributes);
}

// Example on using this function
// The attribute parameter that you pass along must contain all attributes for your product in one go
// so that the wcproduct_set_attributes function can insert them into the correct meta field.
$my_product_attributes = array('hdd_size' => $product->hdd_size, 'ram_size' => $product->ram_size);

// After inserting post
wcproduct_set_attributes($post_id, $my_product_attributes);

// Woohay done!

如果其他人需要在 WooCommerce 中以编程方式导入多个属性,我希望此功能能对其有所帮助!

I hope this function will help other people if they need to import multiple attributes pro-grammatically in WooCommerce!

这篇关于Wordpress Woocommerce - 使用 update_post_meta 添加产品属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆