在 save_post 上设置产品重量的挂钩 [英] Hook to set product weight on save_post

查看:25
本文介绍了在 save_post 上设置产品重量的挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用 save_post 钩子设置产品重量?

Is there a way to set product weight with save_post hook?

我有以下代码,但我不知道如何覆盖权重:

I've following code, but I don't know how to overwrite weight:

add_action( 'save_post', 'change_weight' );
function change_weight($post_id) {
    $WC_Product = wc_get_product($post_id);
}

推荐答案

如果你使用 woocommerce_process_product_meta_$product_type 那么您就不必担心随机数了搭载 WooCommerce 的健全性检查.

If you use the woocommerce_process_product_meta_$product_type then you don't have to worry about nonces as you can piggy back on WooCommerce's sanity checks.

// This will work in both WC 2.6 and WC 2.7
add_action( 'woocommerce_process_product_meta_simple', 'so_42445796_process_meta' );
function so_42445796_process_meta( $post_id ) {
    $weight = 100;
    update_post_meta( $post_id, '_weight', $weight );
}

WC 2.7 将引入抽象数据保存方式的 CRUD 方法.我怀疑他们最终会将产品和产品元数据从默认的 WordPress 表中移出,但我不能确定.在 2.7 中,您可以使用 woocommerce_admin_process_product_object 钩子在保存之前修改 $product 对象.

WC 2.7 will introduce CRUD methods that abstract how the data is saved. I suspect they will eventually move products and product meta out of default WordPress tables, but I can't know for sure. In 2.7 you can use the woocommerce_admin_process_product_object hook to modify the $product object before it is saved.

// Coming in WC2.7 you can use the CRUD methods instead
add_action( 'woocommerce_admin_process_product_object', 'so_42445796_process_product_object' );
function so_42445796_process_product_object( $product ) {
    $weight = 100;
    $product->set_weight( $weight );
}

这篇关于在 save_post 上设置产品重量的挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆