第一次运行时,脚本会抛出“无效分类法”错误,第二次运行时,它会正常摄取。当使用 xdebug 暂停时,它会正确触发,因此似乎是时间门问题。我注意到第一次运行后,全局属性没有分配任何术语,而第二次运行后,所有内容都被正确分配。 有问题的区块
if (! $term = get_term_by( 'name', $option, $term_name )) { // $option='Small', $term_name='pa_size'
// WP_Error Invalid Taxonomy
wp_insert_term( $option, $term_name );
$term = get_term_by( 'name', $option, $term_name );
}
也尝试过
wp_set_object_terms($po->get_id(), $option, $term_name, true );
完整代码
// Add global attributes.
$global_attributes = ['Size', 'Colour'];
foreach ($global_attributes as $global_attribute) {
wc_create_attribute([
'name' => $global_attribute,
'type' => 'text',
]);
}
// Add product.
$product_attributes = [
'Size' => ['Small', 'Large', 'Medium'],
'Colour' => ['Red', 'Blue', 'Green'],
'Rating' => '5 Star!'
];
$product = new \WC_Product();
foreach ($product_attributes as $name => $value) {
$attribute = new \WC_Product_Attribute();
$attribute->set_name($name);
$attribute->set_options([$value]);
if(is_array($value)) {
$attribute->set_options($value);
}
if (in_array($name, $global_attributes)) {
// Convert name to pa_name
$term_name = wc_attribute_taxonomy_name( $name );
$options = [];
if(is_array($value)) {
foreach($value as $option) {
if (! $term = get_term_by( 'name', $option, $term_name )) {
// WP_Error Invalid Taxonomy
wp_insert_term( $option, $term_name );
$term = get_term_by( 'name', $option, $term_name );
}
$options[] = $term->term_id;
}
} else {
if (! $term = get_term_by( 'name', $value, $term_name )) {
wp_insert_term( $value, $term_name );
$term = get_term_by( 'name', $value, $term_name );
}
$options[] = $term->term_id;
}
$attribute->set_id(wc_attribute_taxonomy_id_by_name( $name ));
$attribute->set_name($term_name);
$attribute->set_options($options);
}
}
$product->save();
上找到的自定义函数
wc_create_attribute()
的调用替换了createAttribute()
。注册分类法将在页面加载时发生,因为立即需要分类法,所以我们自己注册。
function createAttribute(string $attributeName, string $attributeSlug): ?\stdClass {
delete_transient('wc_attribute_taxonomies');
\WC_Cache_Helper::incr_cache_prefix('woocommerce-attributes');
$attributeLabels = wp_list_pluck(wc_get_attribute_taxonomies(), 'attribute_label', 'attribute_name');
$attributeWCName = array_search($attributeSlug, $attributeLabels, TRUE);
if (! $attributeWCName) {
$attributeWCName = wc_sanitize_taxonomy_name($attributeSlug);
}
$attributeId = wc_attribute_taxonomy_id_by_name($attributeWCName);
if (! $attributeId) {
$taxonomyName = wc_attribute_taxonomy_name($attributeWCName);
unregister_taxonomy($taxonomyName);
$attributeId = wc_create_attribute(array(
'name' => $attributeName,
'slug' => $attributeSlug,
'type' => 'text'
));
register_taxonomy($taxonomyName, apply_filters(
'woocommerce_taxonomy_objects_' . $taxonomyName,
array(
'product'
)
),
apply_filters('woocommerce_taxonomy_args_' . $taxonomyName,
array(
'labels' => array(
'name' => $attributeSlug,
),
'hierarchical' => FALSE,
'show_ui' => FALSE,
'query_var' => TRUE,
'rewrite' => FALSE,
)
)
);
}
return wc_get_attribute($attributeId);
}