在产品属性中添加新术语并在Woocommerce中的产品中进行设置

时间:2018-12-10 11:51:40

标签: php wordpress woocommerce product custom-taxonomy

我的自定义分类法(WooCommerce属性)已经存在,并且我正在使用以下内容为分类法添加新术语并将其与我的WooCommerce产品相关联:

wp_set_object_terms($product_id, array($omega_jahr), 'pa_years-of-construction');

当我使用以下代码为产品调用“ pa_years_of_construction”时,我可以看到新条款已保存:

$v = array_values( wc_get_product_terms( $product->id, 'pa_years-of-construction', array( 'fields' => 'names' ) ) );

但是,当我在网站的后台和前端检查产品属性时,没有显示“ pa_years_of_construction”归因。

我在这里想念什么?

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

产品属性是一种复杂的自定义分类法,比简单的代码行还需要更多...

以下代码将处理所有现有商品属性的情况:

$taxonomy = 'pa_years-of-construction'; // The taxonomy

$term_name = '2009'; // The term "NAME"
$term_slug = sanitize_title($term_name); // The term "slug"

// Check if the term exist and if not it create it (and get the term ID).
if( ! term_exists( $term_name, $taxonomy ) ){
    $term_data = wp_insert_term( $term_name, $taxonomy );
    $term_id   = $term_data['term_id'];
} else {
    $term_id   = get_term_by( 'name', $term_name, $taxonomy )->term_id;
}

// get an instance of the WC_Product Object
$product = wc_get_product( $product_id );

$attributes = (array) $product->get_attributes();

// 1. If the product attribute is set for the product
if( array_key_exists( $taxonomy, $attributes ) ) {
    foreach( $attributes as $key => $attribute ){
        if( $key == $taxonomy ){
            $options = (array) $attribute->get_options();
            $options[] = $term_id;
            $attribute->set_options($options);
            $attributes[$key] = $attribute;
            break;
        }
    }
    $product->set_attributes( $attributes );
}
// 2. The product attribute is not set for the product
else {
    $attribute = new WC_Product_Attribute();

    $attribute->set_id( sizeof( $attributes) + 1 );
    $attribute->set_name( $taxonomy );
    $attribute->set_options( array( $term_id ) );
    $attribute->set_position( sizeof( $attributes) + 1 );
    $attribute->set_visible( true );
    $attribute->set_variation( false );
    $attributes[] = $attribute;

    $product->set_attributes( $attributes );
}

$product->save();

// Append the new term in the product
if( ! has_term( $term_name, $taxonomy, $product_id ))
    wp_set_object_terms($product_id, $term_slug, $taxonomy, true );

经过测试可以正常工作。

相关问题