2

How do I enqueue a script on the header if the user is on an archive page of a custom post type? The custom post type is called limitedrun and the page is called archive-limitedrun.php.

I tried this and got no response:

function opby_theme() {
wp_register_script('responsive-img', get_template_directory_uri() .'/js/responsive-img.min.js', array('jquery'));
wp_enqueue_script('responsive-img');
wp_enqueue_style( 'opby', get_stylesheet_uri() );
wp_register_style('googleFonts', 'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter');
wp_enqueue_style( 'googleFonts');
if (is_singular('limitedrun') ) {
wp_register_style('ltd-run-font', 'https://fonts.googleapis.com/css?family=Roboto:100,500');
wp_enqueue_style( 'ltd-run-font');
}
}
add_action( 'wp_enqueue_scripts', 'opby_theme' );  
6

You can save your time and server load by not using wp_register_script and wp_register_style when you don't need them definitely. wp_enqueue_style and wp_enqueue_script do the same job themselves when not involving excessive functions.

Here is easier and more readable code up to date with the accepted answer by @vancoder:

<?php
function opby_theme()
{
    wp_enqueue_script(
        'responsive-img',
         get_template_directory_uri() .'/js/responsive-img.min.js',
         array('jquery')
    );

    wp_enqueue_style(
        'opby',
        get_stylesheet_uri()
    );

    wp_enqueue_style(
        'googleFonts',
        'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter'
    );

    if ( is_post_type_archive('limitedrun') ) {
        wp_enqueue_style(
            'ltd-run-font',
            'https://fonts.googleapis.com/css?family=Roboto:100,500'
        );
    }
}
add_action( 'wp_enqueue_scripts', 'opby_theme' );
0
3

is_singular doesn't handle archives.

Try

is_post_type_archive( 'limitedrun' );
0

You can use the template_redirect action hook for exactly that.

This hook is the point where WordPress knows which templates the user is viewing and gets fired just before the template files are loaded.

Here is an example, where a stylesheet is only loaded for the post archive:

`

// Call the hook and register your function
add_action( 'template_redirect', 'register_styles_for_post_archive' );

// Call your function which enqueues the stylesheet only for the post archive
function register_styles_for_post_archive() {

// put in your post type as a parameter or leave empty for the actual post type
    if ( is_post_type_archive( $post_types ) ) {
        wp_enqueue_style('your-custom-stylesheet-name', 'your-css-file.css', false, 01, 'screen');

    }
}

`

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.