Woocommerce产品发布、更新和删除挂钩

7
我需要WooCommerce产品发布、更新和删除的钩子,如果有人知道,请告诉我。
我找到了这个钩子:
add_action('transition_post_status', 'wpse_110037_new_posts', 10, 3);
 function wpse_110037_new_posts($new_status, $old_status, $post) {
 if( 
        $old_status != 'publish' 
        && $new_status == 'publish' 
        && !empty($post->ID) 
        && in_array( $post->post_type, 
            array( 'product') 
            )
        ) {
          //add some cde here
     }

  }

但它只显示产品 ID、标题、发布状态等......但我想要产品价格、类别、标签、品牌和库存状态。如果有人知道,请回复我。谢谢,Ketan。
4个回答

17

Woocommerce产品基本上是WordPress文章。您可以使用WordPress挂钩

add_action( 'before_delete_post', 'wpse_110037_new_posts' );
add_action( 'save_post', 'wpse_110037_new_posts' );

function wpse_110037_new_posts($post_id){
    $WC_Product = wc_get_product( $post_id);
}

wc_get_product()将返回WC_Product对象,您可以从中获取产品详细信息。


6
最好检查一下是否为“产品”,否则它将适用于所有帖子类型。 - brettwhiteman
8
为什么不使用 post_type 保存帖子钩子,而不是使用 save_post 并检查 post_type?可以尝试使用 save_post_product 钩子。 - Jeremy

7

我更喜欢检查状态是否为非草稿状态。另外,您可以使用第三个参数update来检查它是否为更新。

add_action( 'save_post', array($this, 'wpse1511_create_or_update_product' ), 10, 3);

function wpse1511_create_or_update_product($post_id, $post, $update){
    if ($post->post_status != 'publish' || $post->post_type != 'product') {
        return;
    }

    if (!$product = wc_get_product( $post )) {
        return;
    }

    // Make something with $product
    // You can also check $update
}

7

save_postsave_post_product 钩子在更新post_meta之前运行,而大多数 WooCommerce 产品数据都存储为post_meta,因此使用它们可能会导致问题。

值得庆幸的是,自v3以来,有特定的 WooCommerce 钩子,在产品更新后 (woocommerce_update_product) 和创建产品时 (woocommerce_new_product) 运行。

add_action( 'woocommerce_new_product', 'on_product_save', 10, 1 );
add_action( 'woocommerce_update_product', 'on_product_save', 10, 1 );
function on_product_save( $product_id ) {
     $product = wc_get_product( $product_id );
     // do something with this product
}

1
我尝试了这种方法,但它没有起作用。 - huypham
@huypham 当然可以工作,这些操作钩子是 WC 核心的一部分。如果您将上面的片段复制并粘贴,那么显然它什么也不会做。 - GeorgeP

0

这个钩子将在WC更新数据库中的产品后运行:

add_action('save_post_product', 'ns_sync_on_product_save', 10, 3);

function ns_sync_on_product_save( $post_id, $post, $update ) {
   $product = wc_get_product( $post_id );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接