根据 Woocommerce 结帐中的复选框自定义字段在项目名称下添加文本

Add a text under item name based on checkbox custom field in Woocommerce checkout

我有一个自定义函数来检查复选框是否被选中,如果是,它会在价格旁边添加 'with vat relief'。如果未选中,它会在价格旁边添加 'inc vat'。效果很好,我的代码是:

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 );
function conditional_price_suffix( $price, $product ) {
   $isTaxRelefe = get_post_meta($product->id, 'disability_exemption', true);

   if ($isTaxRelefe == 'yes')
       $price .= ' ' . __('with vat relief');

    else $price .= ' ' . __('inc vat');

   return $price;
}

我现在需要做的是添加另一个针对结帐页面的功能,该功能说明如果复选框被选中,则会在产品标题下方显示一些文本,但我正在努力。我最初的想法是编辑 /checkout/review-order 所以我添加了一个 if else 语句来输出产品标题旁边的内容。我补充说:

$isTaxRelefe = get_post_meta($product->id, 'disability_exemption', true);

if ($isTaxRelefe == 'yes') {
   $content .= 'VAT RELIEF AVAILABLE';    
}

但这没有任何作用,我尝试了各种变体,更改为 echo 语句等,但没有成功。我确定我只是写错了。谁能建议?我不太了解的是 WordPress 的功能,就好像我可以编写一个仅针对结帐页面的功能一样,我不确定它如何确定输出您的位置。 if else 语句似乎是显而易见的选择,但运气不佳。

您的代码有点过时,您应该在第一个函数中使用 $product->get_id() 自 Woocommerce 3 而不是 get_post_meta() 函数中的 $product->id

您也可以直接使用产品 object 中的 WC_Data 方法 get_meta()

以下是您重新访问的代码,其中包含附加的挂钩函数,该函数将有条件地在结帐页面的产品标题下显示 "VAT RELIEF AVAILABLE" 文本:
(不覆盖模板 review-order.php

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 );
function conditional_price_suffix( $price, $product ) {
    if ( $product->get_meta('disability_exemption') === 'yes')
        $price .= ' ' . __('with vat relief');
    else
        $price .= ' ' . __('inc vat');

   return $price;
}

add_filter( 'woocommerce_checkout_cart_item_quantity', 'custom_text_below_checkout_product_title', 20, 3 );
function custom_text_below_checkout_product_title( $quantity_html, $cart_item, $cart_item_key ){
    if ( $cart_item['data']->get_meta('disability_exemption') === 'yes' )
        $quantity_html .= '<br>' . __('VAT RELIEF AVAILABLE');

    return $quantity_html;
}

代码进入活动 child 主题(活动主题)的 function.php 文件。已测试并有效。