Load scripts based on post type

Is there a nice way to load a js file based on the post type being viewed?

I have a supplier which has a map on it but I only want the load the js when a single one is being viewed. I load the script in my functions.php file.

Related posts

Leave a Reply

2 comments

  1. If you hook onto a later action such as template_redirect, you should be able to check the query vars to determine if your specific post type is being viewed.

    add_action( 'template_redirect', 'example_callback' );
    
    function example_callback() {
        if( is_single() && get_query_var('your-posttype') )
            wp_enqueue_script( .. your args .. );
    }
    

    Or alternatively like this…

    add_action( 'template_redirect', 'example_callback' );
    
    function example_callback() {
        if( is_single() && get_query_var('post_type') && 'your-type' == get_query_var('post_type') )
            wp_enqueue_script( .. your args .. );
    }
    

    Hope that helps.

  2. you can use this code:

    add_action('admin_init','load_my_script');
    function load_my_script() {
      global $typenow;
      if (empty($typenow) && !empty($_GET['post'])) {
        $post = get_post($_GET['post']);
        $typenow = $post->post_type;
      }
      if (!is_admin() && is_single() && $typenow=='your post type') {
        //load your script here
      }
    }