我的产品有一个自定义元'wccaf_virtual_quantity'
。现在,我想计算并添加另一个自定义元'actual_stock'。 'actual_stock'
= stock
-wccaf_virtual_quantity
的值
我正在尝试的代码破坏了我的网站,导致访问管理面板时出现'The site is experiencing technical difficulties. Please check your site admin email inbox for instructions.'
错误。但是当我从数据库中禁用代码并检查产品表'actual_stock'
时,我可以看到'actual_stock'
的值已更新。
这意味着代码可以正常工作,但是会破坏正在处理的网站。
我尝试将以下代码添加到functions.php
中。我正在使用“代码段”插件添加php代码段
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$products_array = get_posts($args);
if (!empty($products_array)) {
// loop through each product
foreach ($products_array as $product)
{
update_actual_stock($product->ID);
}
}
function update_actual_stock($post_id) {
$post_type = get_post_type($post_id);
if ($post_type == 'product') {
$product = wc_get_product($post_id);
$virtual_stock = get_post_meta( $post_id,
'wccaf_virtual_quantity', true );
$visible_stock = $product->get_stock_quantity();
$actual_quantity = $visible_stock - $virtual_stock;
update_post_meta( $post_id, 'actual_stock',$actual_quantity);
}
}
请检查我在做什么错。
答案 0 :(得分:1)
为什么必须在每个请求上运行该功能?
当然,您的代码可能会杀死您的服务器,它会被管理员或前端的每个请求触发,并且它的查询和循环遍历所有帖子,然后更新所有产品帖子,
您应该将其挂在某处,例如创建/更新帖子时
结帐save_post功能
//Your function to update the meta
function update_actual_stock($post_id) {
$post_type = get_post_type($post_id);
if ($post_type == 'product') {
$product = wc_get_product($post_id);
$virtual_stock = get_post_meta( $post_id, 'wccaf_virtual_quantity', true );
$visible_stock = $product->get_stock_quantity();
$actual_quantity = $visible_stock - $virtual_stock;
update_post_meta( $post_id, 'actual_stock',$actual_quantity);
}
}
// hook it on 'save_post' action hook so it only updates meta of specific post if its updated/created
function _update_blabla_meta( $post_id ) {
update_actual_stock($post_id)
}
add_action( 'save_post', '_update_blabla_meta' );
如果您需要在下订单后运行函数,则必须将其挂接到woocommerce_checkout_order_processed
上,该操作do_action( 'woocommerce_checkout_order_processed', $order_id, $posted_data, $order );
上会传递三个参数,供您获取要更新的帖子>
在此处https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#1120
中检查代码编辑。...
这应该可以实现您想要的,或者只是对其进行修改以满足您的需求;
//run meta update on products only after order is place
add_action( 'woocommerce_checkout_order_processed', function($order_id) {
$order = wc_get_order( $order_id ); // get the order from ID
$items = $order->get_items(); // get order items
//Loop through order each items
foreach ( $items as $item ) {
$porduct_id = $item->get_product_id(); //get the product ID from order item
$virtual_stock = get_post_meta( $porduct_id, 'wccaf_virtual_quantity', true ); // get your own meta value
$visible_stock = get_post_meta( $porduct_id, '_stock', true ); // get the product current stock count
$actual_quantity = $visible_stock - $virtual_stock;
update_post_meta( $porduct_id, 'actual_stock', $actual_quantity); // Update your own meta
}
});