I have a function that will initialize an image slider in my WordPress theme, however I can’t get the PHP variables to be passed into it. Here is the code:
function slideshowSettings ($pause_time) {
$code = "<script>
jQuery(function(){
jQuery('#camera_wrap_3').camera({
height: '40%',
thumbnails: true,
time: ".$pause_time.",
fx: '".$transition_effect."',
transPeriod: ".$transition_speed.",
autoAdvance: ".$auto_advance.",
minHeight: '50px',
mobileNavHover: false,
imagePath: '".get_template_directory_uri()."/images/'
});
});
</script>";
echo $code;
}
add_action('wp_head', 'slideshowSettings');
The variables are assigned above the function but the output I get from the function looks like this:
<script>
jQuery(function(){
jQuery('#camera_wrap_3').camera({
height: '40%',
thumbnails: true,
time: ,
fx: '',
transPeriod: ,
autoAdvance: ,
minHeight: '50px',
mobileNavHover: false,
imagePath: 'http://www.brainbuzzmedia.com/themes/simplybusiness/wp-content/themes/simplybusiness/images/'
});
});
</script>
How can I pass those variables?
You can’t add arguments to the
wp_head
because none are passed to your hooked function whendo_action('wp_head');
is called by thewp_head()
function. The arguments foradd_action()
aredo_action
however)If you need to be able to pass these values in outside of your hooked function to
wp_head
, I would useapply_filters
to modify a value:The correct way of passing PHP variables to Javascript is using
wp_localize_script
.Check this article by Otto. And this Q&A at WordPress StackExghange.
In your Question you don’t show where those variables are coming from, hence they are printing… nothing.
I just made a test. This creates the options values in the database.
And this, an adapted version of your code:
Which results in this being printed in the
<head>
of the site:You can pass the number of arguments after the priority argument in add_action()
The wordpress codex has some examples about it.
You should note that your function is taking only on argument actually, and you’re using undefined variables like
$transition_effect
,$transition_speed
and$auto_advance
in that function.