为 wordpress 的单选按钮的标签元素添加一个 id 或 class

Add an id or class to the label element of a radio button for wordpress

在结帐页面中,我想添加单独的图像而不是每个单选按钮。 I found how to do this here.

这里的问题是我无法向标签元素添加单独的 ID 或 class,似乎需要用实际图像替换单选按钮。低于我到目前为止所得到的。我无法像 GitHub 线程中显示的那样专门针对标签。

有人知道如何使用 PHP 或 JavaScript 添加 class 吗?或者任何其他方式。

提前致谢!

这里是HTML:

<span class="woocommerce-input-wrapper">

    <input type="radio" class="input-radio " value="Banana" name="radioButtonForm" id="radioButton1">
    <label for="radioButton1" class="radio ">Banana</label>
    
    <input type="radio" class="input-radio " value="Apple" name="radioButtonForm" id="radioButton2">
    <label for="radioButton2" class="radio ">Apple</label>
    
    <input type="radio" class="input-radio " value="Pear" name="radioButtonForm" id="radioButton3">
    <label for="radioButton3" class="radio ">Pear</label>
    
    <input type="radio" class="input-radio " value="Tomato" name="radioButtonForm" id="radioButton4">
    <label for="radioButton4" class="radio ">Tomato</label>
    
</span>

这里是 CSS:

.woocommerce-input-wrapper input{
    margin:0;padding:0;
    -webkit-appearance:none;
       -moz-appearance:none;
            appearance:none;
}


#radioButton1 .radio{
    background-image:url(http://i.imgur.com/SJbRQF7.png);
}

#radioButton2 .radio{
    background-image:url(http://i.imgur.com/lXzJ1eB.png);
}

#radioButton3 .radio{
    background-image:url(http://i.imgur.com/SJbRQF7.png);
}

#radioButton4 .radio{
    background-image:url(http://i.imgur.com/lXzJ1eB.png);
}

我们可以使用 preg_replace 来定位我们的标签标签并添加我们的 类.

<?php
add_action( 'wp_loaded', function() {
  function wp_custom_radio_add_class( $subject ) {
    if( ! is_admin() && is_checkout() || is_page( 'checkout' ) ) {
      $search = [
        '/<label for="radioButton1" class="radio ">/',
        '/<label for="radioButton2" class="radio ">/',
        '/<label for="radioButton3" class="radio ">/',
        '/<label for="radioButton4" class="radio ">/',
        // ... etc.
      ];
      $replace = [
        '<label for="radioButton1" class="radio label_custom_class_1">',
        '<label for="radioButton2" class="radio label_custom_class_2">',
        '<label for="radioButton3" class="radio label_custom_class_3">',
        '<label for="radioButton4" class="radio label_custom_class_4">',
        // ... etc.
      ];
      $subject = preg_replace( $search, $replace, $subject );
      return $subject;
    };
  };
  ob_start( 'wp_custom_radio_add_class' );
} ); ?>

如果我对您的问题的理解正确,则您不必一定要将自定义 idclass 添加到您的标记中。将 CSS 选择器切换为使用 + -sibling 选择器应该就足够了。我制作了一个 JSFiddle 来演示这种解决方案:

https://jsfiddle.net/6rsf79xz/