php - WooCommerce:将产品属性添加到产品中的现有属性

标签 php wordpress woocommerce attributes product

我正在努力为产品添加属性。

我有一组要添加到产品中的关键字:

$clean_keywords = array('cake','cup cakes');
$term_taxonomy_ids = wp_set_object_terms( get_the_ID(), $clean_keywords, 'pa_keywords', true );
$thedata = Array('pa_keywords' => Array(
    'name' => 'pa_keywords',
    'value' => '',
    'is_visible' => '0',
    'is_taxonomy' => '1'
));

update_post_meta( get_the_ID(),'_product_attributes',$thedata);

这工作正常,但它删除了我附加到产品的所有其他属性。

我认为解决方案是获取当前属性并将其与 $thedata 变量合并...但不确定如何执行此操作。

有什么想法吗?

谢谢

最佳答案

您需要先获取现有的产品属性,然后在保存之前将新的产品属性插入到数组中。我还在数组中添加了 2 个缺少的参数......

所以你的代码应该是:

$product_id = get_the_ID();
$taxonomy = 'pa_keywords';
$clean_keywords = array('cake','cup cakes');
$term_taxonomy_ids = wp_set_object_terms( $product_id, $clean_keywords, $taxonomy, true );

// Get existing attributes
$product_attributes = get_post_meta( $product_id, '_product_attributes', true);

// get the count of existing attributes to set the "position" in the array
$count = count($product_attributes);

// Insert new attribute in existing array of attributes (if there is any)
$product_attributes[$taxonomy] = array(
    'name' => $taxonomy,
    'value' => '',
    'position' => $count, // added
    'is_visible' => '0',
    'is_variation' => '0', // added (set the right value)
    'is_taxonomy' => '1'
);

// Save the data
update_post_meta( $product_id, '_product_attributes', $product_attributes );

这应该可以在不删除现有数据的情况下工作。

关于php - WooCommerce:将产品属性添加到产品中的现有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413936/

相关文章:

wordpress - 从 Load Balancer 后面的 AWS certificate Manager 使用 SSL 设置 wordpress 网站

apache - htaccess : 301 redirect removing part of url

php - 检查是否在数组中然后在数组中的更好方法

php - git push php 和主机 key 验证失败

php - 无法在 "localhost"端口 25 连接到邮件服务器

php - 无法更改 Woocommerce "Thank you"消息

css - 仅在桌面上隐藏 Logo [wordpress]

wordpress - 将自定义 CSS 类添加到 WooCommerce 结帐字段

wordpress - 错误 Woocommerce REST API 扩展订单 "line_items"响应

php - 从 PHP 页面使用 GMail SMTP 服务器发送电子邮件