Web Designing, Web Development, Website Design, Website Development, SEO

0091 98233 72069

COGS: CUSTOMISED, OPTIMISED, GENERALISED WEB DESIGN & WEB DEVELOPMENT SOLUTIONS

WordPress conditionally load css or javascript for shortcode

Most of the plugins or themes developers loads style sheet and / or js files related to specific shortcode even if that shortcode is not used in page content. Though there is no direct method available for conditionally loading style sheet or javascript js file below is a work around.

For js file this can be achieved by two ways. One of those methods is printing javascript file in footer. This can be done using three actions as per example below

add_action(‘init’, ‘register_js_script’);

add_action(‘wp_footer’, ‘print_js_script’);

function register_js_script() {

wp_register_script(‘my-js-script’, plugins_url(‘my-script.js’, __FILE__));

}

function print_js_script() {

global $my_shortcode_exists;

if ( ! $my_shortcode_exists )

return;

wp_print_scripts(‘my-js-script’);

}

add_shortcode(‘myshortcode’, ‘my_shortcode_handler’);

function my_shortcode_handler($atts) {

global $my_shortcode_exists;

$my_shortcode_exists = true;

// shortcode handling logic below

}

Above method is useful for javascript files because javascript can be printed in head or body. But this method is not useful for stylesheet because css file or style should be printed within head tag. Printing style or css link within body will not work in few browsers or is not good practice.

For css style sheet file this can be achieved using “get_shortcode_regex” function. See example below

function my_detect_shortcode()
{
    global $post;
    /* if post variable is not available then find post id using url */
    if (!isset($post) || !is_object($post))
   {
      $post = get_post(url_to_postid( "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] ));
   }
    $pattern = get_shortcode_regex();

    if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
        && array_key_exists( 2, $matches )
        && in_array( 'my-shortcode', $matches[2] ) )
    {
        // shortcode is being used hence enque my css and js
    } 
} 

add_action( 'wp', 'your_prefix_detect_shortcode' );