Posted By

zac on 05/29/11


Tagged

wordpress


Versions (?)

Enqueue again


 / Published in: PHP
 

URL: http://beerpla.net/2010/01/13/wordpress-plugin-development-how-to-include-css-and-javascript-conditionally-and-only-when-needed-by-the-posts/

This simple function fires before the header gets printed, as it's attached to the 'the_posts' hook. However, this time it has full access to the posts' content.

  1. add_filter('the_posts', 'conditionally_add_scripts_and_styles'); // the_posts gets triggered before wp_head
  2. function conditionally_add_scripts_and_styles($posts){
  3. if (empty($posts)) return $posts;
  4.  
  5. $shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued
  6. foreach ($posts as $post) {
  7. if (stripos($post->post_content, '[code]')) {
  8. $shortcode_found = true; // bingo!
  9. break;
  10. }
  11. }
  12.  
  13. if ($shortcode_found) {
  14. // enqueue here
  15. wp_enqueue_style('my-style', '/style.css');
  16. wp_enqueue_script('my-script', '/script.js');
  17. }
  18.  
  19. return $posts;
  20. }

Report this snippet  

You need to login to post a comment.