0

I want to conditionally enqueue a script and stylesheet depending on whether the [gallery] shortcode is used in posts. Here is how I am doing it (based on):

function doraemon_scripts() {

    if( is_single() ) {

        if (strpos($post->post_content,'[gallery') === false){
        } else {
            wp_enqueue_style( ... );
            wp_enqueue_script( ... );
        }

    }

}
add_action( 'wp_enqueue_scripts', 'doraemon_scripts' );

But the problem is, the stylesheet and script aren't being enqueued, as it seems, strpos is always returning false. What could I be doing wrong here?

2

You will need global $post to get the $post variable into the scope of that function.

function doraemon_scripts() {

    if( is_single() ) {
      global $post;
        if (strpos($post->post_content,'[gallery') === false){
        } else {
//             wp_enqueue_style( ... );
//             wp_enqueue_script( ... );
        }

    }

}
add_action( 'wp_enqueue_scripts', 'doraemon_scripts' );

Using the $post global outside of the Loop is not always reliable, but WordPress will set that variable to the first post in the result set which will be the correct post on single post pages, but won't be right on other pages.

Of course, that won't work if something else has altered the global, and you can't always predict what a plugin will do and where.

You might be safer using ...

global $wp_query;
$post = $wp_query->posts[0];
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.