Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load certain scripts only on single pages of custom post type in wordpress?

Tags:

wordpress

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?

like image 379
Jagan K Avatar asked Nov 22 '13 06:11

Jagan K


People also ask

How do I display a single custom post type in WordPress?

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 post type?

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).

How to insert JavaScript into WordPress page?

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.

Can you add custom JavaScript in WordPress?

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.


2 Answers

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');
like image 164
jogesh_pi Avatar answered Oct 14 '22 01:10

jogesh_pi


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');
like image 29
nomeq Avatar answered Oct 14 '22 03:10

nomeq