Woocommerce - 挂钩设置产品重量save_post
问题描述:
有没有一种方法来设置产品重量与save_post挂钩?Woocommerce - 挂钩设置产品重量save_post
我下面的代码,但我不知道怎么改写重量:
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的健康检查中捎带。
// 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中,您可以使用3210钩子在保存之前修改对象$product
。
// 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);
}
答
要设置权重,您需要更新后期元。这是可以做到这样的:在上面的代码
update_post_meta($post_id, '_weight', $weight);
$权重是包含要的重量是值的变量。然而,每次保存任何帖子时都会触发save_post钩子,因此博客帖子,页面,产品等等。您可能想要验证该帖子是否为产品。你可以是这样做的:
if (get_post_type ($post_id) == 'shop_order') {
update_post_meta($post_id, '_weight', $weight);
}
此外,如果你希望你改变它,你可以像这样做之前得到产品的当前重量:
$product = wc_get_product($post_id);
$weight = $product->get_weight();