Untitled
unknown
plain_text
2 years ago
2.1 kB
5
Indexable
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) {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
if ($product->is_on_sale()){
echo wc_format_sale_price($regular_price, $sale_price);
} else {
echo wc_price($regular_price);
}
}
}
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 usersEditor is loading...
Leave a Comment