php - 在 WooCommerce 中保存订单后,保存自定义项目元数据

标签 php wordpress woocommerce product hook-woocommerce

我正在使用save_post_{$post->post_type}钩子(Hook),一旦保存帖子(订单)就会触发。

目的是根据某些订单状态保存产品元数据。这是我为此编写/使用的代码:

add_action ( 'save_post_shop_order', function (int $postId, \WP_Post $post, bool $update): void   {

        
    $order = new WC_Order( $postId );
    
    $order_status = $order->get_status();
    $status_arrays = array( 'processing', 'on-hold', 'to-order', 'needed' );
    
    if ( in_array($order_status, $status_arrays) ) {
        return;
    }
        
    $items = $order->get_items();
    
     foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $product    = wc_get_product( $product_id );
        $final_product->update_meta_data( '_test', '_test' );
        $final_product->save();

    }

   },
    10,
    3
);

但是,我在数据库中找不到新的元数据。有什么建议吗?谁能帮助我如何实现这一目标?

最佳答案

您的代码包含一些错误,例如$final_product 不等于 $product,因此未定义。

这应该足够了:(通过注释标签进行解释,添加到代码中)

function action_save_post_shop_order( $post_id, $post, $update ) {
    // Checking that is not an autosave && current user has the specified capability
    if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! current_user_can( 'edit_shop_order', $post_id ) ) {
        return;
    }
    
    // Get $order object
    $order = wc_get_order( $post_id );

    // Is a WC_Order
    if ( is_a( $order, 'WC_Order' ) ) {
        // NOT has status
        if ( ! $order->has_status( array( 'processing', 'on-hold', 'to-order', 'needed' ) ) ) { 
            // Loop through order items
            foreach( $order->get_items() as $item ) {
                // Get an instance of corresponding the WC_Product object
                $product = $item->get_product();
                
                // Meta: key - value
                $product->update_meta_data( '_test', '_test' );
                
                // Save
                $product->save();
            }
        }
    }
}
add_action( 'save_post_shop_order', 'action_save_post_shop_order', 10, 3 );

注意:如果订单应该具有某种状态而不是不具有该状态,只需删除! 来自:

// NOT has status
if ( ! $order->has_status(..

关于php - 在 WooCommerce 中保存订单后,保存自定义项目元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69427248/

相关文章:

php - 将 Google 搜索结果读入 PHP 数组?

php - 如何从 CakePHP 中的 Controller 访问助手?

html - 第 n 个子选择器不适用于 Wordpress 主题

php - 如何更改 WordPress 上的博客页面 url

php - 按 WooCommerce 管理订单列表中的特定元字段过滤订单

php - 将延期交货库存状态添加到 Woocommerce 可变产品下拉列表中

php - 如何强制 Jooma!以HTML 格式发送电子邮件?

javascript - 为 ipad mini 调试 wordpress

php - 如何测试数组中的部分字符串值

php - 如何在 "woocommerce_thankyou"钩子(Hook)触发后将产品名称与其属性名称连接起来?