motorfirebox
motorfirebox

Reputation: 65

Best practice for including a JavaScript on certain WordPress pages

I need to include a JavaScript file on certain specific pages of my WordPress site. The way I'm handling in currently is that I'm parenting all the pages to a particular parent page, and including the JavaScript on pages that have the specified parent.

This works, but it seems a little clunky. Is there a better way to include a JavaScript file on an essentially arbitrary set of pages?

Here's what I'm using currently, to give you an idea of what I'm looking for:

function include_crm_wp_funcs(){
  global $post;
  if( get_the_title($post->post_parent) == 'My Parent Page' ){
    require_once 'myJavaScript.js';
  }
}
add_action('wp_enqueue_scripts','include_crm_wp_funcs');

Upvotes: 0

Views: 106

Answers (1)

RRikesh
RRikesh

Reputation: 14381

function include_crm_wp_funcs(){
  global $post;
  if( get_the_title($post->post_parent) == 'My Parent Page' ){
     wp_register_script( 'js_name', get_template_directory_uri() . 'PATH TO YOUR JS FILE' );
     wp_enqueue_script( 'js_name' );
  }
}
add_action('wp_enqueue_scripts','include_crm_wp_funcs');

You need to put the javascript file in your theme directory and call it using wp_register_script() and wp_enqueue_script.

Upvotes: 1

Related Questions