I needed a way to filter a page/posts content before it was loaded so I could add scripts to the header if a specific shortcode was present. After much searching I came across this on http://wpengineer.com
function has_my_shortcode($posts) {
if ( empty($posts) )
return $posts;
$found = false;
foreach ($posts as $post) {
if ( stripos($post->post_content, '[my_shortcode') )
$found = true;
break;
}
if ($found){
$urljs = get_bloginfo( 'template_directory' ).IMP_JS;
wp_register_script('my_script', $urljs.'myscript.js' );
wp_print_scripts('my_script');
}
return $posts;
}
add_action('the_posts', 'has_my_shortcode');
which is absolutely brilliant and did exactly what I needed.
Now I need to extend it a bit further and do the same for sidebars. It can be by a particular widget type, shortcode, code snippet or anything else that would work to identify when the script needs to be loaded.
The problem is I can't figure out how to access the sidebars content before the sidebar is loaded (the theme in question will have several sidebars)