phpjquerywordpresswoocommerce

Format Woocommerce variations price


I am adding prices to the WooCommerce variations dropdown menu and then changing the dropdown menu to radio buttons. This works great but I need to style the prices.

The PHP adds the price to the dropdown options:

if( !is_admin() ) {
    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 = $_product->get_price();

                if ( $data == $term ) {
                    $html = $term;
                    $html .= '-' . $display_price;
                    return $html;
                }
            }
        }
        return $term;
    }
}

The jQuery changes the dropdown menu to radio buttons and labels.

$('.variations select').each(function (i, select) {
    var $select = jQuery(select);
    $select.find('option').each(function (j, option) {
        var $option = jQuery(option);
        // Create a radio:
        var $radio = jQuery('<input type="radio" />');
        // Set name and value:
        $radio.attr('name', $select.attr('name')).attr('value', $option.val());
        // Set checked if the option was selected
        if ($option.attr('selected')) $radio.attr('checked', 'checked');
        // Insert radio after select box:
        $select.after($radio);
        $radio.wrap('<div class="variation-wrap" />');
        // Insert a label:
        $radio.after(
            $("<label />").attr('for', $select.attr('name')).text($option.text())
        );
    });
});

How can I add a span tag around the prices so that I can style it?


Solution

  • I didn't find a way to do this server side so I went with a jQuery solution found here.

    $('.variation-wrap label').html(function () {
        var text = $(this).text().split('-');
        var last = text.pop();
        return text.join(" ") + (text.length > 0 ? ' <span class="last">$' + last + '</span>' : last);
    });