Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Created June 5, 2016 20:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikeschinkel/5d43b23110fa23f733e01e02fb521755 to your computer and use it in GitHub Desktop.
Save mikeschinkel/5d43b23110fa23f733e01e02fb521755 to your computer and use it in GitHub Desktop.
Example of how to use WordPress' wp_localize_script() script to provide number of page children to a jQuery script
<?php
// Your other your-theme/functions.php code goes here
add_action( 'wp_enqueue_scripts', 'yoursite_enqueue_scripts' );
function yoursite_enqueue_scripts() {
global $post;
if ( ! empty( $post ) && is_page( $post ) ) {
wp_enqueue_script( 'yoursite-js', get_stylesheet_directory_uri() . '/js/yoursite.js');
wp_localize_script( 'yoursite-js', 'YourSiteVar', array(
'childCount' => count( get_children( $post->ID ) ),
) );
}
}
// {theme_dir}/js/yoursite.js
(function($) {
$(document).ready(function(){
// Inspired by https://www.youtube.com/watch?v=PDd8shcLvHI
if ( 0 == YourSiteVar.childCount ) {
alert('Yes, we have NO CHILDREN on this page today!');
} else {
alert('No, we have %d CHILDREN on this page today!'.replace(/%d/g,YourSiteVar.childCount) );
}
});
})(jQuery); // Fully reference jQuery after this point.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment