php片段分解了网站



我的产品具有自定义的meta 'wccaf_virtual_quantity'。现在,我想计算并添加另一个自定义元'META" MATEA"'。'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);   
}
}

请检查我做错了什么。

为什么您必须在每个请求上运行该功能?

off ofcourse,您的代码可以杀死您的服务器,它是针对管理或前端的每个请求触发的,并且通过所有帖子进行查询和循环,然后更新所有产品帖子,

您应该将其连接到某个地方,例如创建/更新

结帐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 );上有三个参数,供您抓取以更新的帖子

在此处查看代码

编辑....

这应该实现您想要的东西,或者简单地修改它以适合您的需求;

//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
    }
});

最新更新