How to pass parameter from another php file using wp_localize_script

I’ve a post type called “rooms” and there is a meta variable like $max_person for every room. In single-rooms.php
all what I need is to pass $max_person to an external javascript file

This is what I wrote in function.php

Read More
add_action("wp_enqueue_scripts", function() {

    if (is_single()) {
        if (get_post_type() == 'rooms') {
            $max_person = get_post_meta($post->ID,'max_person',true);
            $combo_parameters = array(
                'max' => $max_person
            );

            wp_enqueue_script('room_combobox', get_template_directory_uri() . '/js/room_combobox.js', array( 'jquery' ), '1.0' ,true);
            wp_localize_script( 'room_combobox', 'ComboParameters', $combo_parameters );

        }
    }
});

and this is my javascript file

function room_combobox() {
    var text = "";
    var i;
    var x =  ComboParameters.max;

    for (i = 0; i <= x; i++) {
        text += "<option value="+i+">"+i+"</option>" +"<br>";
    }
    document.getElementById("combo").innerHTML = '<select name= "room-adults" id= "single-room-adult-selection"><option>No. adults</option>'+text+x+'</select>';
}

jQuery(document).ready(function() {
    room_combobox()
});

for some reasons ComboParameters.max = 0

Related posts

Leave a Reply

1 comment