我有这个功能,可以将自定义元字段添加到所有 WooCommerce 电子邮件中的产品详细信息中。但我只需要在订单付款后显示(这也可以只是“已完成”电子邮件)。
add_action( 'woocommerce_order_item_meta_start', 'email_confirmation_display_order_items', 10, 3 );
function email_confirmation_display_order_items( $item_id, $item, $order ) {
// On email notifications for line items
if ( ! is_wc_endpoint_url() && $item->is_type('line_item') ) {
$ot_address = get_post_meta( $item->get_product_id(), 'ot_address', true );
if ( ! empty($ot_address) ) {
printf( '<div>' . __("Terms: %s", "woocommerce") . '</div>', $ot_address );
}
}
}
我希望可以将它嵌套在 if ( $email->id == 'customer_completed_order' ) {} 内,所以最终的代码将如下所示:
add_action( 'woocommerce_order_item_meta_start', 'email_confirmation_display_order_items', 10, 3 );
function email_confirmation_display_order_items( $item_id, $item, $order ) {
if ( $email->id == 'customer_completed_order' ) {
// On email notifications for line items
if ( ! is_wc_endpoint_url() && $item->is_type('line_item') ) {
$ot_address = get_post_meta( $item->get_product_id(), 'ot_address', true );
if ( ! empty($ot_address) ) {
printf( '<div>' . __("Terms: %s", "woocommerce") . '</div>', $ot_address );
}
}
}
}
但在更改后它就停止工作了。有什么建议吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
正如您在代码尝试中看到的,
$email不是woocommerce_order_item_meta_start挂钩的一部分。因此,要定位某些 WooCommerce 电子邮件通知,您需要一种解决方法。步骤 1) 通过另一个仅适用于 WooCommerce 电子邮件通知的挂钩创建并添加全局变量。
// Setting global variable function action_woocommerce_email_before_order_table( $order, $sent_to_admin, $plain_text, $email ) { $GLOBALS['email_id'] = $email->id; } add_action( 'woocommerce_email_before_order_table', 'action_woocommerce_email_before_order_table', 1, 4 );步骤 2) 在挂钩
woocommerce_order_item_meta_start中,使用全局变量,以便我们可以定位某些 WooCommerce 电子邮件通知function action_woocommerce_order_item_meta_start( $item_id, $item, $order, $plain_text ) { // On email notifications for line items if ( ! is_wc_endpoint_url() && $item->is_type('line_item') ) { // Getting the email ID global variable $ref_name_globals_var = isset( $GLOBALS ) ? $GLOBALS : ''; $email_id = isset( $ref_name_globals_var['email_id'] ) ? $ref_name_globals_var['email_id'] : ''; // NOT empty and targeting specific email. Multiple statuses can be added, separated by a comma if ( ! empty ( $email_id ) && in_array( $email_id, array( 'new_order', 'customer_completed_order' ) ) ) { // Get meta $ot_address = get_post_meta( $item->get_product_id(), 'ot_address', true ); // OR use to get meta // $ot_address = $item->get_meta( 'ot_address' ); if ( ! empty( $ot_address ) ) { printf( '' . __( 'Terms: %s', 'woocommerce' ) . ' ', $ot_address );
}
}
}
}
add_action( 'woocommerce_order_item_meta_start', 'action_woocommerce_order_item_meta_start', 10, 4 );