[wp-hackers] checking if post has shortcode, before header is output?

Austin Matzko if.website at gmail.com
Sun Oct 25 01:14:19 UTC 2009


On Fri, Oct 23, 2009 at 6:02 PM, scribu <scribu at gmail.com> wrote:
> Try this:
>
> add_action('template_redirect', 'add_scripts');
>
> function add_scripts() {
> if ( ! is_page() )
> return;
>
> global $posts;
>
> if ( FALSE === strpos($posts[0]->post_content, '[your_shortcode') )
> return;

Rather than checking the global $posts variable, I'd recommend using
the WP_Query API:

add_action('template_redirect', 'add_scripts');
function add_scripts() {
   global $wp_query;
   if ( is_singular() ) {
      $post = $wp_query->get_queried_object();
      if ( false !== strpos($post->post_content, '[your_shortcode') ) {
         wp_enqueue_script(...
      }
   }
}


More information about the wp-hackers mailing list