首页 文章

woocommerce:为产品属性增加 Value

提问于
浏览
13

如何通过代码为woocommerce属性添加值?我创建了一个名为“Dispatch time”的属性(分类:pa_dispatch),现在我想为特定产品的Dispatch属性添加值 .

如何以编程方式执行此操作?

enter image description here

2 回答

  • 14

    我找到了答案,你需要使用wp_set_object_terms设置分类法的对象条款,

    wp_set_object_terms( $object_id, $terms, $taxonomy, $append);
    

    其中,$ append可以是 truefalse ,如果为true,则标记将附加到现有标记,如果为false,则替换标记 .

    在我的例子中,

    wp_set_object_terms( $object_id, '2 Business Days', 'pa_dispatch' , false);
    

    在这里, pa_dispatch 是woo-commerce分类法 .

  • 3

    您无法为属性添加值 . 您需要创建产品变量,创建变体并使用属性进行分配 . 现在,在此变体中,您可以指定一个值 .

    Attributes Configuration

    Variations Configuration

    Read mode:

    EDIT:

    在对问题进行更多澄清之后,这是一个更新的解决方案 .

    将以下函数添加到functions.php中 . 在适当的钩子上调用它并传递产品ID和属性值 .

    function se19519561_set_attributes($post_id, $attributes) {
    
        //Type attribute
        $product_attributes['type'] = array(
            //Make sure the 'name' is same as you have the attribute
            'name' => htmlspecialchars(stripslashes('Dispatch Time')),
            'value' => $attributes,
            'position' => 1,
            'is_visible' => 1,
            'is_variation' => 1,
            'is_taxonomy' => 0
        );
    
    //Add as post meta
    update_post_meta($post_id, '_product_attributes', $product_attributes);
    
    }
    

    希望这可以帮助!

相关问题