Can someone help me with this code? I need to update it so that the calculator’s price is displayed as the final price in the cart for product ID 45255. The ID is automatically fetched, and I also need the customer’s dimensions sent to the calculator to be taken into account. Instead of the fixed dimensions of 40×45, it should use the dimensions entered by the customer during the calculation process.
I would greatly appreciate any assistance with this.
function enqueueCalculatorScript() {
?>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
// Fetch and display dimension ranges
var productTitleElement = document.querySelector('.product_title.entry-title');
var productTitle = productTitleElement.innerText;
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {
'action': 'get_dimension_ranges',
'product_title': productTitle
}, function(response) {
if (!response.error) {
document.getElementById('min_szerokosc').textContent = response.min_width;
document.getElementById('max_szerokosc').textContent = response.max_width;
document.getElementById('min_wysokosc').textContent = response.min_height;
document.getElementById('max_wysokosc').textContent = response.max_height;
}
});
// Elements for calculating price
var widthInput = document.getElementById('product_width');
var heightInput = document.getElementById('product_height');
var calculateButton = document.getElementById('calculate_price');
var priceDisplay = document.getElementById('calculated_price');
calculateButton.addEventListener('click', function() {
var width = widthInput.value;
var height = heightInput.value;
var productTitle = productTitleElement.innerText;
var data = {
'action': 'get_variants_for_calculation',
'width': width,
'height': height,
'product_title': productTitle
};
// Calculate and display price
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
var variants;
try {
variants = JSON.parse(response); // Próbuj przekształcić odpowiedź w obiekt JS
} catch (e) {
console.error("Parsing error:", e);
return;
}
if (variants.error) {
priceDisplay.innerHTML = variants.error;
} else {
var priceHtml = variants.sale_price ?
'<s>' + variants.regular_price + '</s> ' + variants.sale_price :
variants.regular_price;
priceDisplay.innerHTML = 'Cena: ' + priceHtml;
}
});
});
});
</script>
<?php
}
add_action('wp_enqueue_scripts', 'enqueueCalculatorScript');
function getVariantsForCalculation() {
$product_title = isset($_POST['product_title']) ? sanitize_text_field($_POST['product_title']) : '';
$query = new WP_Query([
'post_type' => 'product',
'title' => $product_title
]);
if ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$variants = get_post_meta($post_id, 'custom_variants', true);
$client_width = isset($_POST['width']) ? floatval(sanitize_text_field($_POST['width'])) : 0;
$client_height = isset($_POST['height']) ? floatval(sanitize_text_field($_POST['height'])) : 0;
// Initialize nearest match and distance
$nearestVariant = null;
$smallestDistance = PHP_FLOAT_MAX;
// Iterate over each variant to find the nearest match
foreach ($variants as $variant) {
$variantWidth = floatval($variant['width']);
$variantHeight = floatval($variant['height']);
// Calculate Euclidean distance from the requested size
$distance = sqrt(pow($variantWidth - $client_width, 2) + pow($variantHeight - $client_height, 2));
// Update nearest match if a closer one is found
if ($distance < $smallestDistance) {
$smallestDistance = $distance;
$nearestVariant = $variant;
}
}
if ($nearestVariant) {
$response = [
'regular_price' => $nearestVariant['regular_price'],
'product_id' => $post_id // Include the product ID
];
if (!empty($nearestVariant['sale_price'])) {
$response['sale_price'] = $nearestVariant['sale_price'];
}
echo json_encode($response);
} else {
echo json_encode(['error' => 'No matching variant found']);
}
} else {
echo json_encode(['error' => 'Product not found']);
}
wp_die();
}
// Hook dla użytkowników zalogowanych
add_action('wp_ajax_get_variants_for_calculation', 'getVariantsForCalculation');
// Hook dla użytkowników niezalogowanych
add_action('wp_ajax_nopriv_get_variants_for_calculation', 'getVariantsForCalculation');
// Modify the price in the cart for product ID 45255
function custom_price_for_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['product_id'] == 45255 || ( isset( $cart_item['variation_id'] ) && $cart_item['variation_id'] == 45255 ) ) {
$cart_item['data']->set_price( 15 ); // Set custom price to 15
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'custom_price_for_cart_items', 10, 1 );
function custom_price_html_for_product_id_45255( $price_html, $product ) {
if ( $product->get_id() == 45255 ) {
$price_html = wc_price(15); // Display custom price as 15 zł
}
return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'custom_price_html_for_product_id_45255', 10, 2 );
function custom_price_for_product_45255( $price, $product ) {
if ( $product->get_id() == 45255 ) {
return 15; // Set custom price to 15
}
return $price;
}
if ( !is_admin() ) {
add_filter( 'woocommerce_product_get_price', 'custom_price_for_product_45255', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'custom_price_for_product_45255', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'custom_price_for_product_45255', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'custom_price_for_product_45255', 10, 2 );
}
// Ensure the regular price is the same as the custom price
function set_regular_price_for_product_45255( $regular_price, $product ) {
if ( $product->get_id() == 45255 ) {
return 15; // Set regular price to 15
}
return $regular_price;
}
add_filter( 'woocommerce_product_get_regular_price', 'set_regular_price_for_product_45255', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'set_regular_price_for_product_45255', 10, 2 );
function add_custom_dimensions_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
// Get the product title from the product ID
$product = wc_get_product($product_id);
$product_title = $product ? $product->get_title() : '';
// Use WP_Query to get the ID based on the title
$query = new WP_Query([
'post_type' => 'product',
'title' => $product_title
]);
if ($query->have_posts()) {
$query->the_post();
$queried_product_id = get_the_ID();
// Compare with the queried product ID
if ( $product_id == $queried_product_id || $variation_id == $queried_product_id ) {
$cart_item_data['custom_dimensions'] = '40x45';
}
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_dimensions_to_cart_item', 10, 3 );
function display_custom_dimensions_in_cart( $item_data, $cart_item ) {
if ( array_key_exists( 'custom_dimensions', $cart_item ) ) {
$item_data[] = array(
'name' => 'Wymiary',
'value' => $cart_item['custom_dimensions']
);
}
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_custom_dimensions_in_cart', 10, 2 );
function add_custom_dimensions_to_order_items( $item, $cart_item_key, $values, $order ) {
if ( array_key_exists( 'custom_dimensions', $values ) ) {
$item->add_meta_data( 'Wymiary', $values['custom_dimensions'] );
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_dimensions_to_order_items', 10, 4 );