Conditional Loading of Scripts


/ Published in: PHP
Save to your folder(s)

Example of loading thickbox and syntaxhighlighter conditionally from the functions.php of a wordpress theme.


Copy this code and paste it in your HTML
  1. add_action('wp_print_styles','my_conditional_script');
  2.  
  3. function my_conditional_script() {
  4. global $post;
  5. if (is_single() && strpos($post->post_content, 'class="thickbox"') !== false) {
  6. wp_enqueue_script('thickbox');
  7. wp_enqueue_style('thickbox');
  8. }
  9.  
  10. if (is_single() && strpost($post->post_content, '<pre') !== false) {
  11. $style = get_stylesheet_directory_uri() . '/syntaxhighlighter/style.css';
  12. wp_register_style('sh-style', $style);
  13. wp_enqueue_style('sh-style');
  14. $script = get_stylesheet_directory_uri() . '/syntaxhighlighter/script.js';
  15. wp_register_style('sh-script', $script);
  16. wp_enqueue_style('sh-script');
  17. }
  18. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.