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' );
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' );