問(wèn)題描述
我的自定義分類法(WooCommerce 屬性)已經(jīng)存在,我正在使用以下內(nèi)容向分類法添加新術(shù)語(yǔ)并將其與我的 WooCommerce 產(chǎn)品相關(guān)聯(lián):
My custom taxonomy (WooCommerce attribute) already exists and I am using the following to add a new term to the taxonomy and associate it with my WooCommerce product:
wp_set_object_terms($product_id, array($omega_jahr), 'pa_years-of-construction');
當(dāng)我使用以下內(nèi)容為我的產(chǎn)品調(diào)用pa_years_of_construction"時(shí),我可以看到新條款已被保存:
When I use the following to call the 'pa_years_of_construction' for my product, I can see that the new terms have been saved:
$v = array_values( wc_get_product_terms( $product->id, 'pa_years-of-construction', array( 'fields' => 'names' ) ) );
但是,當(dāng)我在網(wǎng)站的后臺(tái)和前端檢查我的產(chǎn)品屬性時(shí),沒(méi)有顯示pa_years_of_construction"屬性.
However, when I check my product attributes in the backed and frontend of my website, the 'pa_years_of_construction' attribution isn't showing up.
我在這里遺漏了什么?
在此先感謝您的幫助!
推薦答案
產(chǎn)品屬性是一個(gè)復(fù)雜的自定義分類法,需要的不僅僅是一行簡(jiǎn)單的代碼...
Product attributes are a complicated custom taxonomy that needs much more than a simple line of code...
以下代碼將處理預(yù)先存在的產(chǎn)品屬性的所有情況:
The following code will handle all cases for a pre-existing product attribute:
$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 );
經(jīng)過(guò)測(cè)試并有效.
這篇關(guān)于向產(chǎn)品屬性添加新術(shù)語(yǔ)并將其設(shè)置在 Woocommerce 的產(chǎn)品中的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!