如何解决根据WooCommerce产品库存自动更新产品自定义字段
我在产品上附加了一个ACF字段“ DeliverySpeed”,其值为“快”和“慢”
每当产品库存为零或更少(有待补货的产品)时,我想更新此字段以将其值更改为“慢”
到目前为止,我仍在学习PHP,但这是我要去的东西,但是我确定缺少了很多东西,我只是不知道该朝哪个方向前进:
基于acf update field documentation
function automatically_change_delivery( ) {
global $product;
$fieldkey = "DeliverySpeed";
$valueslow = "Slow";
if($product->get_stock_quantity()<0) { update_field( $field_key,$valueslow,$post_id );
} }
在此先感谢您的关注和建议。
解决方法
一旦订单减少了产品库存水平,以下代码将自动更新您的产品自定义字段。因此,当产品有库存时,自定义字段值将为“快速”,否则为“慢”。
代码:
add_action( 'woocommerce_payment_complete','update_product_custom_field_after_reduced_stock_levels',20,2 );
add_action( 'woocommerce_order_status_completed',2 );
add_action( 'woocommerce_order_status_processing',2 );
add_action( 'woocommerce_order_status_on-hold',2 );
function update_product_custom_field_( $order_id,$order = '' ) {
// Continue only when order has reduced product stock levels
if ( wc_string_to_bool( get_post_meta( $order_id,'_order_stock_reduced',true ) ) )
return $order_id; // Exit
if( ! $order || ! is_a( $order,'WC_Order') ) {
$order = wc_get_order( $order_id ); // Get the WC_Order object if it's empty
}
$field_key = 'DeliverySpeed';
// Loop through order items
foreach ( $order->get_items() as $item ) {
$product = $cart_item['data'];
$product_id = $product->get_id();
$stock_qty = $product->get_stock_quantity();
$field_value = get_field( $field_key,$product_id ); // Get ACF field value
if ( $stock_qty <= 0 && $field_value === 'Fast' ) {
update_field( $field_key,'Slow',$product_id );
}
elseif ( $stock_qty > 0 && $field_value === 'Slow' ) {
update_field( $field_key,'Fast',$product_id );
}
}
}
代码进入活动子主题(或活动主题)的functions.php文件中。应该可以。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。