Include PHP variables into jQuery

Posted on 25th September, 2013 1 Comment

There is a simple answer to this problem…
To use PHP in jQuery you just need to add the jQuery to a .php document.
I’m using the Cycle.js slider plugin in my 3x examples below. Which is plucked from this article Responsive Custom Post Type Slider

If you would like to add an options page, which uses the built in theme customizer which has shipped as part of WordPress since 3.6 read it here.

Begin by creating a file called js.php and add it to your themes js folder. – theme-folder / js / js.php


ex.1 – Fire the Js only if you’re on a particular page.

* Simple example of firing the js if we’re on the home page of our theme.

<script type="text/javascript">
jQuery(document).ready(function($) {

<?php 	
	if ( is_home() ) { 	  
	// This is the homepage activate the cycle plugin
   	  $('#cycle').cycle(); 	
	} else {    	 
	// This is not a homepage do nothing...
 	} 
?>
});
</script>

ex.2 – Allowing user specified options.

* Adding user defined options to a plugin is just as simple, below I’ve given the end user flexibility by allowing them more control of; In this case a Slider.

<script type="text/javascript">
jQuery(document).ready(function($) {

$'#cycle').cycle({
	fx: '<?php echo get_option('slider_transition') ?>',
	timeout: <?php echo get_option('slider_interval') ?>,
	easing: '<?php echo get_option('easing_effect')?>',
	speed: <?php echo get_option('slider_speed') ?>,
	fit: 1,
	next: '#next',
	prev: '#prev'
 });

});
</script>

.ex3 – Activating plugin options if the PHP variable matches a certain criteria.

Adding an If statement to the plugins options.

<script type="text/javascript">
<?php $slider = get_option('wp_slideshowsource');  ?>

jQuery(document).ready(function($) {

$('#cycle').cycle({
	fx: 'fade',
	timeout: 3000,
	next: '#next',
	prev: '#prev'
	<?php if ($slider == "Recent Listings") { ?> // If it's the recent listings CPT show the pager.
		, pager: '.slidernav'
	<?php } ?>
 });

});
</script>

To call the js.php just include it in the header or in your footer.php with:

<?php include 'js/js.php'; ?>

Now go create!!!

Comments

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]