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
–
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
The problem was that the
$post
variable wasn’t declared as global, soget_post_meta
failed because it wasn’t passed a valid post ID.Just add
global $post
to the beginning of the function to reference the global variable.See php docs here: http://php.net/manual/en/language.variables.scope.php