保存产品时,我想检查该产品是否具有特定属性。就我而言,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 );
}
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
第一个 $post 不是对象。将返回 ID,这很好。
add_action('woocommerce_update_product', 'save_product_region'); function save_product_region( $product_id ) { //Get product object from the ID $_product = wc_get_product($product_id); $attributes = $_product->get_attributes(); $add_option = wp_set_object_terms( $product_id, 'canada', 'pa_region', true ); $curr_options = $attributes['pa_region']['options']; //Check if we have this attribute set already if(!in_array($add_option,$curr_options)): $updated_options = array_push($curr_options,$add_option); $data = array( 'pa_region' => array( 'name'=>'pa_region', 'options'=> $updated_options, 'is_visible' => '1', 'is_variation' => '0', 'is_taxonomy' => '1' ) ); //First getting the Post Meta $_product_attributes = get_post_meta($product_id, '_product_attributes', TRUE); //Updating the Post Meta update_post_meta($product_id, '_product_attributes', array_merge($_product_attributes, $data)); endif; }