0

I use this function to add prices to my WooCommerce variation dropdown menu. I am trying to wrap the price with a span tag but it's displaying the tags as text.

add_filter( 'woocommerce_variation_option_name','display_price_in_variation_option_name');
function display_price_in_variation_option_name( $term ) {
    global $product;
    if ( empty( $term ) ) {
        return $term;
    }
    if ( empty( $product->get_id() ) ) {
        return $term;
    }
    $variation_id = $product->get_children();
    foreach ( $variation_id as $id ) {
        $_product       = new WC_Product_Variation( $id );
        $variation_data = $_product->get_variation_attributes();
        foreach ( $variation_data as $key => $data ) {
            $display_price = '';
            switch ($id) {
                case 1:
                    $display_price = $_product->get_price() / 12;
                    break;
                case 2:
                    $display_price = $_product->get_price();
                    break;
                case 3:
                    $display_price = $_product->get_price() / 6;
                    break;
                default:
            }           
            if ( $data == $term ) {
                $html = $term;
                $html .= '<span>' . $display_price . '</span>';
                return $html;
            }
        }
    }
    return $term;
}
1

You can't add HTML inside <option> tags, which the variation dropdowns use. It's invalid HTML.

Permitted content Text, possibly with escaped characters (like é).

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

  • I am using jQuery to replace the variation dropdown menu with radio buttons and labels. I see the issue now, thanks. – yourbudweiser Mar 1 '19 at 15:31
1

In addition to Jacob's answer, if you look at where the woocommerce_variation_option_name filter is applied in WooCommerce, you can see this:

<?php echo esc_html( apply_filters( 'woocommerce_variation_option_name', $option->name ) ); ?>

This means that any HTML is escaped via esc_html, so < becomes &lt;, etc.

  • 1
    Right. And the reason the HTML is escaped like this is at least partly because no tags are allowed. – Jacob Peattie Mar 1 '19 at 14:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.