How to enqueue different scripts & styles for a Custom Post Type in functions.php

Viewed 851

I have two functions to enqueue my scripts. I want to call one function if the post is a custom post type, and the other for all other posts and pages.

How add conditional logic in functions.php to do this? Typical Wordpress functions(get_the_ID, is_post_type and others) are not working in functions.php.

This is my code:

// How Add Conditional Logic ?
add_action( 'wp_enqueue_scripts', 'theme_media_new' );


// Use fot All pages to site
function theme_media() {
  wp_enqueue_style( 'main-css', get_template_directory_uri() . '/static/css/main.min.css"' );
  wp_enqueue_script( 'common-js', get_template_directory_uri() . '/static/js/main.js', array(), '1.0.0', true );

}
// Use Only for custom post type 'coaching'
function theme_media_new(){

  wp_enqueue_style( 'main-new-css', get_template_directory_uri() . '/static_new/css/main.min.css"' );
  wp_enqueue_script( 'common-new-js', get_template_directory_uri() . '/static_new/js/main.min.js', array(), '1.0.0', true );

}
1 Answers

You put the conditional logic into the function you add to add_action. In that function you can check for the post type/archive and calof the functions you want for that page.

I'm not sure if you want to do this for a Custom Post Type archive or post (or both), so I've included the checks for both, you can change the code to suit what you need it to do.

add_action( 'wp_enqueue_scripts', 'my_enqueue_styles_scripts' );

function my_enqueue_styles_scripts(){

    // load scripts for ALL pages if you have any...

    // Now check for your CPT and load the extra scripts:
    // Load scripts only on CPT POSTS of type "coaching"
    if ( is_singular( 'coaching' ) )
        theme_media_new(); 

    // otherwise load scripts for all other pages
    else
        theme_media();
}

If you want to load the scripts on the archive page for the custom post types, you can use this instead of is_singular

    // Load scripts only for the ARCHIVE for the CPT "coaching"
    if ( is_post_type_archive( 'coaching' ) ) 
        theme_media_new(); 
Related