gpt4 book ai didi

php - 使用 woocommerce hook 获取最近添加的产品

转载 作者:搜寻专家 更新时间:2023-10-31 21:22:56 24 4
gpt4 key购买 nike

我想在从 Woocommerce 管理员添加产品后发送 API 请求。实际上我想要的是,当用户向他的商店添加新产品(类(class))时,API 请求将创建一个与 LMS 中的产品同名的类(class)。

我已成功 Hook 产品创建事件,但不知道如何获取我在 woocommerce 中创建或添加的产品的数据。

这是我的代码:

add_action('transition_post_status', 'product_add', 10, 3);
function product_add($new_status, $old_status, $post) {
if(
$old_status != 'publish'
&& $new_status == 'publish'
&& !empty($post->ID)
&& in_array( $post->post_type,
array( 'product')
)
) {
//here I want to get the data of product that is added
}
}

此代码运行良好,当我添加产品并在此函数内回显某些内容时,它运行良好。

只想获取产品的Name和Id。

谢谢。

最佳答案

此时,很容易获得与您发布的产品相关的任何数据,甚至更容易获得产品 ID 和产品名称。您将在下面找到从您的产品中获取任何相关数据的所有可能性中的大部分:

add_action('transition_post_status', 'action_product_add', 10, 3);
function action_product_add( $new_status, $old_status, $post ){
if( 'publish' != $old_status && 'publish' != $new_status
&& !empty($post->ID) && in_array( $post->post_type, array('product') ) ){

// You can access to the post meta data directly
$sku = get_post_meta( $post->ID, '_sku', true);

// Or Get an instance of the product object (see below)
$product = wc_get_product($post->ID);

// Then you can use all WC_Product class and sub classes methods
$price = $product->get_price(); // Get the product price

// 1°) Get the product ID (You have it already)
$product_id = $post->ID;
// Or (compatibility with WC +3)
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

// 2°) To get the name (the title)
$name = $post->post_title;
// Or
$name = $product->get_title( );
}
}

代码进入您活跃的子主题(或主题)的 function.php 文件或任何插件文件。

一切都经过测试并且可以正常工作。


引用:Class WC_Product methods

关于php - 使用 woocommerce hook 获取最近添加的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42557637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com