在Woocommerce中将术语设置为产品属性

时间:2015-09-16 05:27:10

标签: woocommerce

我设法在激活插件时添加一个产品属性。这是脚本。

function mycbgenie_add_product_attributes() {

    global $wpdb;

    $insert = $wpdb->insert(
    $wpdb->prefix . 'woocommerce_attribute_taxonomies',
        array(
            'attribute_label'   => 'Sold Through',
            'attribute_name'    => 'sold-through',
            'attribute_type'    => 'text',
            'attribute_orderby' => 'order_by',
            'attribute_public'  => 1
        ),
            array( '%s', '%s', '%s', '%s', '%d' )
    );

    if ( is_wp_error( $insert ) ) {
        throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $insert->get_error_message(), 400 );
    }

    // Clear transients
    delete_transient( 'wc_attribute_taxonomies' );

}

我们如何通过脚本向这个新添加的属性添加一些术语到特定帖子?我的意思是我们如何在下面的代码中引用这个属性

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

1 个答案:

答案 0 :(得分:-1)

您需要先更新条款,然后再更新update_post_meta

//ensure to replace 123 with a valid product id & 'term name' with a valid term 
wp_set_object_terms( 123, "term name", "pa_sold-through", true);

$product_attributes['pa_sold-through'] = array(
        //Make sure the 'name' is same as you have the attribute
        'name' => htmlspecialchars(stripslashes('Sold Through')),
        'value' => 'term name',  //replace 'term name' with a valid term
        'position' => 1,
        'is_visible' => 1,
        'is_variation' => 1,
        'is_taxonomy' => 0
    );

//Add as post meta, ensure to replace 123 with a valid product id
update_post_meta(123, '_product_attributes', $product_attributes);