我有一个表格可以将新书提交到我的WooCommerce网站.我以前只把书的状态保存为产品属性.

// Set the book's condition

$condition = $_POST['condition'];
wp_set_object_terms( $product_id, $condition, 'pa_condition', true );

$att_condition = Array('pa_condition' =>Array(
       'name'=>'pa_condition',
       'value'=>$condition,
       'is_visible' => '1',
       'is_taxonomy' => '1'
     ));

update_post_meta( $product_id, '_product_attributes', $att_condition);

这很容易.现在,我试图添加书籍作者的姓名和流派,但当我复制代码时,它只设置了最后一个产品属性.我知道我可能应该把它放在一个循环中,但我很愚蠢,否则我就不知道我错过了什么.

$condition = $_POST['condition'];
$genre = $_POST['genre'];
$author = $_POST['author'];
    
wp_set_object_terms( $product_id, $condition, 'pa_condition', true );

$att_condition = Array('pa_condition' =>Array(
       'name'=>'pa_condition',
       'value'=>$condition,
       'is_visible' => '1',
       'is_taxonomy' => '1'
     ));

update_post_meta( $product_id, '_product_attributes', $att_condition);

wp_set_object_terms( $product_id, $genre, 'pa_genre', true );

$att_condition = Array('pa_genre' =>Array(
       'name'=>'pa_genre',
       'value'=>$genre,
       'is_visible' => '1',
       'is_taxonomy' => '1'
     ));

update_post_meta( $product_id, '_product_attributes', $att_genre);

wp_set_object_terms( $product_id, $author, 'pa_author', true );

$att_author = Array('pa_author' =>Array(
       'name'=>'pa_author',
       'value'=>$author,
       'is_visible' => '1',
       'is_taxonomy' => '1'
     ));

update_post_meta( $product_id, '_product_attributes', $att_author);

推荐答案

我在https://stackoverflow.com/a/45475863/12092133上找到了答案.

我将表单变量放入一个数组中,然后运行这个foreach,它成功了.

$my_product_attributes['condition'] = $_POST['condition'];
$my_product_attributes['genre'] = $_POST['genre'];
$my_product_attributes['authors'] = $_POST['author'];

foreach ($my_product_attributes as $key => $value) {
    $key = 'pa_' . $key;
    $attribute_values = explode(",", $value);

    wp_set_object_terms($product_id, $attribute_values, $key, false);
    $thedata[sanitize_title($key)] = Array(
        'name' => wc_clean($key),
        'value' => $attribute_values,
        'postion' => '0',
        'is_visible' => '1',
        'is_variation' => '0',
        'is_taxonomy' => '1'
    );
    update_post_meta($product_id, '_product_attributes', $thedata);
}

Php相关问答推荐

如果活动订阅者的购物车中有订阅项目,则在WooCommerce签出中显示通知

输入手写CSV时在PHP中进行日期判断

我需要多个SELECT语句的结果(使用由php ECHO创建的表中显示的Limit(X)

如何更改数据表行背景 colored颜色

使用正则表达式搜索两个子字符串(没有重叠/共享字符)

如何将WooCommerce产品属性术语名称显示为链接术语?

如何实现对数据库表中多列的唯一约束?

Laravel服务Provider 没有向服务类注入价值

如何在WordPress REST API中判断应用程序密码

添加不存在的订单元数据以扩展WooCommerce管理订单搜索

PHP 支持 APNG 文件吗?

按日期向 WooCommerce 中的我的帐户订单添加过滤器

PHP API - 本地主机中的 SSL 证书问题

批量更新 WooCommerce 中所有产品的特定自定义字段

无法读取某些 WordPress 主机上的 cookie

如何在WooCommerce中为访客购买者分配自定义客户代码

为什么foreach循环会输出每个结果?

如何用 php ML 解决这个问题?

使用php删除数组中相同数字的所有变体

如何将子查询结果添加到学说 2 中主查询的末尾?