Created
June 5, 2016 20:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ) ), | |
) ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// {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