将 <br> html 标签添加到 WooCommerce 结帐单选按钮表单字段选项

Add a <br> html tag to WooCommerce checkout radio buttons form field options

woocommerce更新前:

   $args = array(
   'type' => 'radio',
   'class' => array( 'form-row-wide', 'update_totals_on_change' ),
   'options' => array(
      '0'   => 'Niet vandaag, misschien later (totally oké) <br />',
      '2'   => 'Drinkt iets van mij (€2) <br />',
      '3'   => 'Van mij krijgt ge een bio thee\'tje (€3) <br />',
      '5'   => 'Vier ze! Ik schenk je een Kombucha (€5)',
   ),
   'label_class' => 'labelafter',
   'default' => $chosen
   );
     
   echo '<div id="checkout-radio">';
   echo '<h3>Wil je mij virtueel trakteren?</h3>';
   woocommerce_form_field( 'radio_choice', $args, $chosen );
   echo '</div>';

我的单选按钮在我的网站结帐页面上显示为垂直对齐

更新后 相同的代码现在 显示 '
'(在第 5 行的单选按钮选项列表中)标签并且不会将 '
' 标签转换为 实际 换行符。

我不知道为什么 wordpress 突然显示标签 iso 正在转换它。 有人有想法吗?

理想情况下,您可能会在 CSS 中解决此问题,只需针对它们并在每个字段上应用 display:block

但除此之外,您可以应用一些 hack。不要使用 HTML <br /> 标记,而是使用一些您知道永远不会存在于任何单选按钮字段中的字符串,这是 HTML-安全的,并在过滤器中将其替换为您的 <br />;

// Pick something you know won't exist
$lineBreakHack = '~!LINE-BREAK!~';

// Woo will call this hook for all radio buttons, not just yours, but that shouldn't be too much of a perf issue
add_filter(
    'woocommerce_form_field_radio',
    function($field, $key, $args, $value){
        return str_replace($lineBreakHack, '<br />', $field);
    }
);

// This is mostly the same except we're concatenating our special string
$args = array(
'type' => 'radio',
    'class' => array( 'form-row-wide', 'update_totals_on_change' ),
    'options' => array(
      '0'   => 'Niet vandaag, misschien later (totally oké)' . $lineBreakHack,
      '2'   => 'Drinkt iets van mij (€2) <br />' . $lineBreakHack,
      '3'   => 'Van mij krijgt ge een bio thee\'tje (€3)' . $lineBreakHack,
      '5'   => 'Vier ze! Ik schenk je een Kombucha (€5)',
    ),
    'label_class' => 'labelafter',
    'default' => $chosen
);

对于自定义结帐单选按钮字段,您可以使用 woocommerce_form_field_radio 复合挂钩添加 <br /> 标签,例如:

add_action( 'woocommerce_form_field_radio', 'customize_form_field_radio', 20, 4 );
function customize_form_field_radio( $field, $key, $args, $value ) {
    if ( ! empty( $args['options'] ) && 'radio_choice' === $key && is_checkout() ) {
        $field = str_replace( '</label><input ', '</label><br /><input ', $field );
        $field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
    }
    return $field;
}

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

不要忘记从选项数组中删除所有 <br />

因此显示将是: