PHP 嵌套函数逻辑错误 - 用 WPML 翻译 functions.php

PHP Nested functions logic error - translating functions.php with WPML

我正在翻译结帐页面上显示的一段文本,其中包含我正在使用的自定义代码。如何在 PHP 中正确使用嵌套函数?

我将 echo 更改为 WPML 可识别的函数,但在前端无济于事。

add_action( 'woocommerce_review_order_before_submit', 'bbloomer_checkout_add_on', 9999 );

function bbloomer_checkout_add_on() {
   $product_ids = array( 14877, 14879, 15493 );
   $in_cart = false;
   foreach( WC()->cart->get_cart() as $cart_item ) {
      $product_in_cart = $cart_item['product_id'];
      if ( in_array( $product_in_cart, $product_ids ) ) {
         $in_cart = true;
         break;
      }
   }
   if ( ! $in_cart ) {
      echo '<h4><b>● Would you like to add 10/20/30 small sample vials?</b></h4>';

      function change_sm_location_search_title( $original_value ) {
    return '<h4><b>' . __('● Would you like to add 10/20/30 small sample vials?','text-domain') . '</b></h4>';
}
add_filter( 'sm-location-search-title', 'change_sm_location_search_title' );

      echo '<p><a class="button" style="width: 140px" href="?add-to-cart=1183"> €1.2 (10) </a><a class="button" style="width: 140px" href="?add-to-cart=9945"> €2.1 (20)</a><a class="button" style="width: 140px" href="?add-to-cart=9948"> €3 (30)</a></p>';
   }
} 

echo stills 出现在前端,但新的文本域功能只出现在后端。

过滤器用于替换值。您应该将过滤器函数声明放在主函数之外,并使用 apply_filters 调用来使用过滤器。

您也可以改用动作钩子。 我建议阅读有关使用挂钩和过滤器的内容:https://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers

为了更好地理解过滤器的工作原理,请在此处回答:https://wordpress.stackexchange.com/questions/97356/trouble-understanding-apply-filters

这应该有效(未经测试)。

add_action( 'woocommerce_review_order_before_submit', 'bbloomer_checkout_add_on', 9999 );

    function bbloomer_checkout_add_on() {
       $product_ids = array( 14877, 14879, 15493 );
       $in_cart = false;
       foreach( WC()->cart->get_cart() as $cart_item ) {
          $product_in_cart = $cart_item['product_id'];
          if ( in_array( $product_in_cart, $product_ids ) ) {
             $in_cart = true;
             break;
          }
       }
       if ( ! $in_cart ) {
          echo apply_filters('sm-location-search-title', 'Would you like to add 10/20/30 small sample vials?');
          echo '<p><a class="button" style="width: 140px" href="?add-to-cart=1183"> €1.2 (10) </a><a class="button" style="width: 140px" href="?add-to-cart=9945"> €2.1 (20)</a><a class="button" style="width: 140px" href="?add-to-cart=9948"> €3 (30)</a></p>';
       }
    }   
    function change_sm_location_search_title( $original_value ) {
      return '<h4><b>' . __($original_value,'text-domain') . '</b></h4>';
    }  
    add_filter( 'sm-location-search-title', 'change_sm_location_search_title');