登录  /  注册
如果产品未设置,则在保存时添加属性:WooCommerce
P粉555682718
P粉555682718 2023-12-13 15:49:42
[PHP讨论组]

保存产品时,我想检查该产品是否具有特定属性。就我而言,pa_region。如果没有,我想将属性集和属性术语添加到产品中。 如果属性 pa_region 已设置,我不想更新/更改它。

我看到有一个名为 wp_set_object_terms 的函数(文档)。我尝试了一些方法,但我认为 update_post_meta 是正确的方法。

从这个答案中我知道如何检查产品是否具有属性。我稍后会添加该检查。

目前我尝试首先添加该属性。目前还无法正常工作。

我在这里发现了类似的问题,我尝试使用该代码来达到我的目的。但这不起作用。我猜原因是该功能需要产品中已有的属性?! 编辑:我检查过。即使在产品中设置了属性 pa_region,代码也不会更新它的值。

这是我当前的代码:

add_action('woocommerce_update_product', 'save_product_region');
function save_product_region( $post )
{
    if( in_array( $post->post_type, array( 'product' ) ) ){

        $test = 'test';
        $product_id = $post->ID;

        $product_attributes = get_post_meta( $product_id ,'_product_attributes', true);
        var_dump($product_attributes);

        // Loop through product attributes
        foreach( $product_attributes as $attribute => $attribute_data ) {
            // Target specif attribute  by its name
            if( 'pa_region' === $attribute_data['name'] ) {
                // Set the new value in the array
                $product_attributes[$attribute]['value'] = $test;
                break; // stop the loop
            }
        }

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

    }
}

P粉555682718
P粉555682718

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学