This following fails to load the scripts in the single pages,
if(is_single( ) ) add_action('wp_enqueue_scripts', 'build_js');
Suppose, If i use
add_action('wp_enqueue_scripts', 'build_js');
the action is performed and scripts are loaded.
I need to perform the action only on single pages of a custom post type. How to do this?
You will need to copy the following code snippet into the template where you wish to display the custom post type. $args = array ( 'post_type' => 'movies' , 'posts_per_page' => 10 ); $the_query = new WP_Query( $args );
is_singular( string|string[] $post_types = '' ): bool. Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types).
Once the plugin is activated, navigate to Settings → Insert Headers and Footers in your WordPress dashboard. You'll see two boxes labeled Scripts in Header and Scripts in Footer. Any code you add to these boxes will be inserted into the header or footer of your site. This is where you'll add your JavaScript.
You can add custom JavaScript to your WordPress site either by using a plugin or by editing your theme or child theme's functions. php file. Using a plugin is the recommended technique if you don't want to edit your source files, as these plugins ensure that your custom scripts load in the right order.
the problem is you have to check for the single page into the function:
function build_js(){
if( is_single() && get_post_type()=='CustomPostTypeName' ){
wp_enqueue_script(....);
}
}
add_action('wp_enqueue_scripts', 'build_js');
instead of
if(is_single( ) ) add_action('wp_enqueue_scripts', 'build_js');
You can simplify the logic further with the Wordpress function is_singular()
instead.
function build_js(){
if( is_singular('CustomPostTypeName') ) {
wp_enqueue_script(....);
}
}
add_action('wp_enqueue_scripts', 'build_js');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With