How to load scripts and stylesheets on specific pages

Loading scripts and stylesheets on specific pages.

Here the code:

add_action( 'wp_enqueue_scripts','jose_load_assets_on_specifiic_pages' ); 
function jose_load_assets_on_specifiic_pages(){
    global $post;
    if( is_object( $post ) && isset( $post->ID ) && in_array( $post->ID,array( 25,72 ) ) ){
        wp_enqueue_style( 'my-style',YOUR_STYLESHEET_URL.'/your-style.css' );
        wp_enqueue_script( 'sicpost',YOUR_SCRIPT_URL.'/your-script.js',array(),null,true );
    }
}

 

Where 25 and 72 are the IDs of the pages where you want to load your stylesheet your-style.css and your script your-script.js.

You will need to replace YOUR_STYLESHEET_URL with the URL of your stylesheet and YOUR_SCRIPT_URL with the URL of your script.

 

 

Loading scripts and stylesheets only if the content has a specific shortcode.

Here the code:

 

add_action( 'wp_enqueue_scripts','jose_load_assets_if_shortcode' );
function jose_load_assets_if_shortcode(){
global $post;
    if( is_object( $post ) && isset( $post->post_content ) && has_shortcode( $post->post_content,'example_shortcode' ) ){
        wp_enqueue_style( 'my-style',YOUR_STYLESHEET_URL.'/your-style.css' );
        wp_enqueue_script( 'sicpost',YOUR_SCRIPT_URL.'/your-script.js',array(),null,true );
    }
}

 

Where example_shortcode is your shortcode.  When the code detects [example_shortcode] it will enqueue your stylesheet and script.

 

Learn more about wp_enqueue_style and wp_enqueue_script in the Codex.

 

Very simple, but many plugins, including the most popular ones, load stylesheets and scripts everywhere, even if you don’t need them.

In those cases, I suggest you disable the entire plugin on the page where you don’t need it by using Freesoul Deactivate Plugins You can download it from the plugin page on the official WordPress repository.