Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend.
This might be a bad practice, feel free to enlighten me.
Example:
Product Attributes:
Total height: 43m
Total length: 55m
PHP queries "Total-height" as Attribute Name and "43m" as Attribute Value.
PHP replaces empty space with "-".
I can't define a javascript var with "-" in var name.
Example: var Total-height = "43m";
How could I fix this issue?
Here is my code.
Thanks in advance.
function product_attribute_dimensions(){
global $product;
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$value = $product->get_attribute($taxonomy);
if ($value) {
$label = get_taxonomy($taxonomy)->labels->singular_name;
$profile_one = $value;
echo '<script>' . $attribute_label_name . ' = "' . $value . '";
</script>';
}
}
My Answer:
the WooCommerce database to fetch these attributes and then echo them out in a script tag like this:
php
$product_id = 123; // example product ID
$total_height = get_post_meta($product_id, 'total_height', true);
$total_length = get_post_meta($product_id, 'total_length', true);
echo '';
This will output a JavaScript object `productAttributes` with the fetched values of total height and total length. You can then use this object in your frontend JavaScript code.
However, it is generally not recommended to echo out variables directly in a script tag like this, as it can lead to security vulnerabilities such as cross-site scripting (XSS) attacks. It is better to use AJAX to fetch the data from the backend and then manipulate it in JavaScript.
Here's an example of how you can modify the fetched variables in PHP before returning them to the frontend for JavaScript:
php
$product_id = 123; // example product ID
$total_height = get_post_meta($product_id, 'total_height', true);
$total_length = get_post_meta($product_id, 'total_length', true);
// Modify the fetched variables
$total_height_meters = $total_height / 100; // convert height from cm to meters
$total_length_meters = $total_length / 100; // convert length from cm to meters
// Return the modified variables to the frontend
echo '';
In this example, we are converting the height and length from centimeters to meters before returning them to the frontend. This allows you to manipulate the data in PHP before sending it to the frontend for JavaScript use.
Rate this post
3 of 5 based on 3115 votesComments