Skip to content
Advertisement

PHP modify fetched variable and return to frontend for JS

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>';
                
        }

}

Advertisement

Answer

try using window["variable_name"] do this:

echo '<script>window["' . $attrname . '"]=' . $attrval

then in your js:

let this_var = window[attrname]

It seems like the clearest shortest way to do this.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement