我使用以下代码添加带有术语的属性:
$taxonomy = 'pa_' . $attr['name']; // The attribute taxonomy
if (!taxonomy_exists($taxonomy)) {
global $wpdb;
$insert = $wpdb->insert(
$wpdb->prefix . 'woocommerce_attribute_taxonomies',
array(
'attribute_name' => $attr['name'],
'attribute_label' => $attr['name'],
'attribute_public' => 0
),
array('%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');
}
if (!term_exists($attr['value'], $attr['name'])) {
wp_insert_term($attr['value'], $attr['name']);
}
$term_slug = get_term_by('name', $attr['value'], $attr['name'])->slug; // Get the term slug
wp_set_post_terms($product_id, $attr['value'], $attr['name'], true);
// Set/save the attribute data in the product variation
update_post_meta($variation_id, 'attribute_' . $taxonomy, $term_slug);
// Assign to the product
wp_set_object_terms($product_id, $attr['value'], $taxonomy, true);
$att = array($taxonomy => array(
'name' => $taxonomy,
'value' => $attr['value'],
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1',
));
update_post_meta($product_id, '_product_attributes', $att);
但是,代码第一次运行时会添加不带术语的属性。如果我第二次运行它,它才会将术语添加到之前添加的属性中。
这是为什么?
编辑:问题似乎从以下行开始:
$term_slug = get_term_by('name', $attr['value'], $attr['name'])->slug
它根本无法识别新创建的分类法。仅在下一次运行时。
但是为什么呢?是否有一个函数可以用来“刷新”属性,或者 $wp_attributes 变量,这似乎密切相关?
谢谢!
最佳答案
如果不查看实时站点,就很难进行调试。不过,我认为这可能与这段代码有关:
if (!term_exists($attr['value'], $attr['name'])) {
wp_insert_term($attr['value'], $attr['name']);
}
在第一次请求时,该术语会被插入,但在进一步请求之前,它不会成为 WordPress 主查询的一部分。
同样,这主要是猜测,因为我需要查看实际的实现。
关于wordpress - WooCommerce - 添加对象术语无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61726322/