Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.8 kB
3
Indexable
Never

function add_product_id_to_price_html( $price_html, $product ) {
    // Add the product ID as a data attribute to the price span
    return '<span class="price" data-id="' . esc_attr( $product->get_id() ) . '">' . $price_html . '</span>';
}
add_filter('woocommerce_get_price_html', 'add_product_id_to_price_html', 10000000, 2);

// Enqueue necessary scripts and pass AJAX URL to JavaScript
function enqueue_and_embed_custom_scripts() {
    wp_enqueue_script('jquery');
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('span.price').each(function() {
                var product_id = $(this).data('id');
                if (product_id) {
                    $.ajax({
                        url: '<?php echo admin_url('admin-ajax.php'); ?>',
                        type: 'POST',
                        data: {
                            'action': 'get_product_price',
                            'product_id': product_id
                        },
                        success: function(response) {
                            $('span.price[data-id="' + product_id + '"]').html(response);
                        }
                    });
                }
            });
        });
    </script>
    <?php
}
add_action('wp_head', 'enqueue_and_embed_custom_scripts');


// Handle the AJAX request to fetch product prices
function get_product_price() {
    if (isset($_POST['product_id'])) {
        $product_id = intval($_POST['product_id']);
        $product = wc_get_product($product_id);
        if ($product) {
        	echo $product->get_price_html();
        }
    }
    wp_die(); 
}
add_action('wp_ajax_get_product_price', 'get_product_price');  // Handling logged-in users
add_action('wp_ajax_nopriv_get_product_price', 'get_product_price');  // Handling non-logged-in users
Leave a Comment