I’m writing a plugin that defines its own CPT “properties” and I want to enqueue a script specifically in single posts.
It runs without my attempt at a conditional statement just fine but I don’t need it to load on every page so I’d like to make this conditional.
This code is in my plugin root just after my includes.
if ( 'properties' == get_post_type() ) {
if (wp_script_is('owl.carousel.js', 'enqueued')) {
return;
} else {
wp_register_script('owl.carousel.min.js', plugin_dir_url(__FILE__) . 'js/owl.carousel.min.js');
wp_enqueue_script('owl.carousel.min.js');
}
}
I’ve also tried is_sigular('properties')
but that didn’t work either.
I must be missing something silly…
1 Answer
Make sure your code runs in wp_enqueue_scripts
action hook.
Also checkout your script handle 'owl.carousel.js'
. In wp_script_is()
, it is not the same than in the 2 later functions in which you enter it as 'owl.carousel.min.js'
.
add_action( 'wp_enqueue_scripts', 'enqueue_properties_scripts' );
function enqueue_properties_scripts() {
if ( 'properties' === get_post_type() ) {
if ( wp_script_is( 'owl.carousel.min.js', 'enqueued' ) ) {
return;
} else {
wp_register_script( 'owl.carousel.min.js', plugin_dir_url( __FILE__ ) . 'js/owl.carousel.min.js' );
wp_enqueue_script( 'owl.carousel.min.js' );
}
}
}