Conditional wp_enqueue_script on a page

For efficiency we are trying to hook some JS scripts only a certain page template of a theme that is to hold a form: page-with-form.php

On the theme functions.php we’ve defined a init_method as such:

Read More
function my_init_method(){

    $dir = get_bloginfo('stylesheet_directory')."/js/jquery.js";
    wp_deregister_script('jquery');
        wp_register_script('jquery',$dir);
    wp_enqueue_script('jquery');

    $dir = get_bloginfo('stylesheet_directory')."/js/jquery.validate.min.js";
    wp_deregister_script('jquery.validate.min');
        wp_register_script('jquery.validate',$dir);
    wp_enqueue_script('jquery.validate.min');

    $dir = get_bloginfo('stylesheet_directory')."/js/funcion.js";
    wp_deregister_script('funcion');
        wp_register_script('funcion',$dir);
    wp_enqueue_script('funcion');
}    

We then expected we could just add at the firts line of page-with-form.php page template (before get_header()) :

add_action('init', 'my_init_method');
  • Is this not possible?
  • Are we forced to add an if rule to the functions.php function to detect that we are on that page?

Code modifications based on answers:
On the page template load the function directly, no need to add_action(“init”…

my_init_method();
...
get_header();

Related posts

Leave a Reply

3 comments

  1. init is much earlier than page template loading and not appropriate place for enqueues (despite many tutorials and docs using it for that).

    Hook your function to wp_enqueue_scripts and make sure you are doing that hooking before wp_head() call in template.

  2. In addition to using the correct hook (as pointed out by @Rarst), you will need to move your functional code to functions.php, and wrap the function contents in an if ( is_page( 'page-with-form' ) ) conditional.

  3. When you loaded your template file, you already passed the 'template_redirect' hook, which is too late (See: Plugin/Action API Reference).

    You need to set the add_action call in your functions.php file, which is loaded before the after_setup_theme hook – which is the first available hook for themes.