wordpress - WooCommerce - 添加对象术语无法正常工作

标签 wordpress woocommerce

我使用以下代码添加带有术语的属性:

$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/

相关文章:

php - 在 Woocommerce 的客户运输部分下向管理用户添加其他字段

wordpress - 如果用户未登录,woocommerce 会提供循环重定向

javascript - woocommerce 的 css 自定义边框

wordpress - Buddypress 链接不起作用

mysql - WordPress(数据库);显示最后修改日期?

php - 从 WooCommerce 中的当前用户订单中获取订单 ID

javascript - WooCommerce 商店页面 : Quantity input on add to cart button

woocommerce - 将自定义字段添加到购物车项目

WordPress/ACF : Sort Posts by multiple fields

javascript - 如何从我的 html 和正文标签中删除 "display: none"