0

Alright so I am trying to check for a shortcode in the post content so that I can enqueue scripts as necessary.

I have this:

    if( plugin_has_shortcode() ) {
        // Load CSS
        wp_enqueue_style( 'plugin-css', 'plugin.css', array(), null );
    }

And here is my plugin_has_shortcode function:

    function plugin_has_shortcode() {
        global $post;

        if ( strpos( $post->post_content, '[shortcode' ) ) {
            return true;
        }

         return false;
    }

This works most of the time. The issue I am having is that when I add the shortcode to the top of the editor [shortcode] and no other content before it then $post->post_content comes back as an empty string and makes my check return false.

The other weird thing is that if I add any content above the shortcode - even just adding a   above it - will make it work as intended.

Has anyone else encountered this? Is it a bug? Is there a way to fix it?

Any and all input much appreciated!

1

If the shortcode is at the very beginning strpos returns 0 which is evaluated as false:

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

http://www.php.net/manual/en/function.strpos.php

So change your code like this:

function plugin_has_shortcode() {
    global $post;
    if ( strpos( $post->post_content, '[shortcode' ) !== false ) {
        return true;
    }
    return false;
}

Or even shorter:

function plugin_has_shortcode() {
    global $post;
    return strpos( $post->post_content, '[shortcode' ) !== false;
}

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.