在WooCommerce中,将订单详细信息元数据显示在结账确认邮件和管理员订单页面中
P粉022140576
2023-08-15 12:06:40
[PHP讨论组]
我们有一些被定义为“套件”的产品。它们是由其他产品组成的产品列表。定义套件的数据存储在元数据数组中。我创建了一个钩子,用于在产品页面和购物车中显示元数据。我需要在“完成的订单电子邮件”和“管理员订单页面”中做类似的事情,但我不知道如何去做。这是我创建的钩子:
<pre class="brush:php;toolbar:false;">add_filter( 'bis_show_kit_meta', 'bis_show_kit_meta_contents', 10, 3 );
function bis_show_kit_meta_contents($productID)
{
global $wpdb;
$postMeta = get_post_meta($productID,'',true);
if ((isset($postMeta['bis_kit_id'])) and ($postMeta['bis_kit_id'][0] > 1)) {
echo 'This is a Kit containing the following items:<br>';
echo $postMeta['bis_kit_type'][0].'<br>';
foreach($postMeta as $kititem) {
foreach ($kititem as $value) {
$newvalue = unserialize($value);
if ($newvalue) {
$newvalue2 = unserialize($newvalue);
if($newvalue2['type']=="kititem"){
echo '<li>' .$newvalue2['quantity']. ' -> ' .chr(9). $newvalue2['name']. '</li>';
}
}
}
}
}
}</pre>
当前函数已经钩入了我的子主题中的相应模板。
我不知道如何将类似的函数应用于<code>customer-completed-email.php</code>文件,也不知道在管理员编辑订单页面中应该在哪里钩入。
我在另一篇帖子中找到了一些代码,看起来类似于我需要做的事情,但我无法弄清楚管理员订单的修改在哪个文件中。
我找到的代码是:
<pre class="brush:php;toolbar:false;">add_action('woocommerce_before_order_itemmeta','woocommerce_before_order_itemmeta',10,3);
function woocommerce_before_order_itemmeta($item_id, $item, $product){
...
}</pre>
非常感谢任何建议
WooCommerce已经有了一堆钩子,你可以在WooCommerce模板中使用它们,而不是添加自己的钩子...
良好的开发规则是首先使用现有的钩子。如果没有方便或可用的钩子,那么你可以通过子主题覆盖WooCommerce模板。为什么?因为模板有时会更新,然后你需要更新编辑过的模板,而钩子则不需要。
对于“客户完成订单”通知,请使用
woocommerce_order_item_meta_end动作钩子,如下所示:// 将email_id设置为全局变量 add_action('woocommerce_email_before_order_table', 'set_email_id_as_a_global', 1, 4); function set_email_id_as_a_global($order, $sent_to_admin, $plain_text, $email = null ){ if ( $email ) { $GLOBALS['email_id_str'] = $email->id; } } // 在“客户完成订单”电子邮件通知中显示自定义订单项元数据 add_action( 'woocommerce_order_item_meta_end', 'custom_email_order_item_meta', 10, 2 ); function custom_email_order_item_meta( $item_id, $item ){ // 获取email ID全局变量 $refGlobalsVar = $GLOBALS; $email_id = isset($refGlobalsVar['email_id_str']) ? $refGlobalsVar['email_id_str'] : null; // 仅适用于“客户完成订单”电子邮件通知 if ( ! empty($email_id) && 'customer_completed_order' === $email_id ) { bis_show_kit_meta_contents( $item->get_product_id() ); } }这将允许你仅在“客户完成订单”通知中显示自定义元数据。
或者,你可以将钩子替换为具有相同函数变量参数的
woocommerce_order_item_meta_start。将代码放在你的子主题的functions.php文件中或插件中。