我正在尝试为Woocommerce开发一个插件,它将新发布的产品信息发送到Telegram频道。我需要在产品发布时获得产品的价格和图像。但是我的代码返回空
我的代码:
add_action('transition_post_status', 'btb_send_telegram_post', 10, 3);
function btb_send_telegram_post( $new_status, $old_status, $post ) {
if(
$old_status != 'publish'
&& $new_status == 'publish'
&& !empty($post->ID)
&& in_array( $post->post_type,array( 'product'))
) {
// product is new published.
$product = wc_get_product ( $post->ID );
$message = $product->get_short_description()."\r\n";
$message .= "price : ". $product->get_price()."\r\n";
$message .= " regular price : ". $product->get_regular_price() ."\r\n";
$message .= "sale price : ". $product->get_sale_price()."\r\n";
btb_send_message($message);
}
我认为这是因为要发布的产品状态发生变化才会完全保存在数据库中。因为当我在发布之前保存草稿时,它会返回正确的价格。就此而言,我需要采取以下两种方法之一:
现在我不知道如何做到上述两种方法。 任何建议将被认真考虑。
谢谢。
答案 0 :(得分:1)
更新2 (产品数据不再为空)
您可以尝试使用 save_post
操作挂钩隐藏的自定义函数:
// Only on WooCommerce Product edit pages (Admin)
add_action( 'save_post', 'send_telegram_post', 50, 3 );
function send_telegram_post( $post_id, $post, $update ) {
if ( $post->post_type != 'product') return; // Only products
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id; // Exit if it's an autosave
if ( $post->post_status != 'publish' )
return $post_id; // Exit if not 'publish' post status
if ( ! current_user_can( 'edit_product', $post_id ) )
return $post_id; // Exit if user is not allowed
// Check if product message has already been sent (avoiding repetition)
$message_sent = get_post_meta( $post_id, '_message_sent', true );
if( ! empty($message_sent) )
return $post_id; // Exit if message has already been sent
## ------------ MESSAGE ------------ ##
// Get active price or "price" (we check if sale price exits)
$price = empty( $_POST['_sale_price'] ) ? $_POST['_regular_price'] : $_POST['_sale_price'];
$message = '';
$rn = "\r\n";
// Title
if( ! empty( $_POST['post_title'] ) )
$message .= 'Title : ' . $_POST['post_title'] . $rn;
// Short description
if( ! empty( $_POST['excerpt'] ) )
$message .= 'Description : ' . $_POST['excerpt'] . $rn;
// Active price
if( ! empty( $price ) )
$message .= 'Price : ' . $price . "\r\n";
// Regular price
if( ! empty( $_POST['_regular_price'] ) )
$message .= 'Regular price : ' . $_POST['_regular_price'] . $rn;
// Sale price
if( ! empty( $_POST['_sale_price'] ) )
$message .= 'Sale price : ' . $_POST['_sale_price'] . $rn;
// Send message custom function
btb_send_message( $message );
// Just for testing (uncomment below to enable):
// update_post_meta( $post_id, '_message_content', $message ); // Message in database
// add custom meta field to mark this product as "message sent"
update_post_meta( $post_id, '_message_sent', '1' );
}
代码进入活动子主题(或活动主题)的function.php文件。经过测试并正常工作。