Using is_page() in functions.php not working at all

Trying to run a custom script on a single page using is_page in functions.php not working at all. I have a function called load_gh_boards that would enquque a script, only on a certain page (79):

function load_gh_boards() {
if( is_page(79) ){
    wp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true );
}}
add_action('wp_enqueue_script', 'load_gh_boards');

This is inside a theme enqueue function that is loading all of my styles and scripts:

function theme_enqueue() {
if ( ! is_admin() ) {

    wp_register_style( 'main-style', get_bloginfo( 'template_directory' ) . '/css/style.css?' . time() );
    wp_enqueue_style( 'main-style' );
    wp_enqueue_script( 'jquery' );
    wp_register_script( 'main-vendor', get_bloginfo( 'template_directory' ) . '/js/vendor.js', array(), '1.0', true );
    ///etc...

    wp_enqueue_script( 'main-vendor' );
    wp_enqueue_script( 'main-script' );

    ///load_gh_boards
}

No result. Any help or insight at all would be appreciated.

5 Answers
5

is_page(79) is asking if the current main query is a page, specifically page 79

But the main query hasn’t happened yet

This function has to be called inside the main loop or at the very least inside the template, but the init hook is way too early for this.

Instead, make sure you use the body class, and load the script on all pages. Then, check if the body tag has the css class page-id-79.

Other Notes

  • You don’t enqueue on the init hook, you’re meant to enqueue on the wp_enqueue_scripts hook
  • It would be simpler to return early e.g. if ( is_admin() ) return;
  • Don’t enqueue jQuery, instead add it as a dependency so WP knows how to output the scripts in the correct order
  • main-style and main-vendor are very generic names, you might encounter clashes, prefix them, e.g. pji-main-vendor
  • theme_enqueue is also a very generic function name, you should prefix that too
  • You can register and enqueue at the same time using wp_enqueue_script. If you pass everything to that function there’s no need to call wp_register_script
  • Indent your code, modern code editors will do this automatically for free, zero effort. Sublime or Atom are examples of free software that will do this for you, there really are no excuses

Leave a Comment