Amar Singh
Amar Singh

Reputation: 5622

JS Script does not get loaded in wordpress via Hooks

I am trying to use hooks for a js script. The script page does not loads . But it loads when I login to wp-admin

in themes functions.php

add_action('init', 'test_ajax_load_scripts');

function test_ajax_load_scripts() { 


    // load our jquery file that sends the $.post request
    wp_register_script( "ajax-test", get_template_directory_uri().'/ajax-test.js', array( 'jquery' ) );

    // make the ajaxurl var available to the above script
    wp_localize_script( 'ajax-test', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );  

    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'ajax-test', get_template_directory_uri() .'/ajax-test.js', array( 'jquery' ));

}

ajax-test.js

jQuery(document).ready( function($) {
    alert("in ajax-testjs");

            });

Upvotes: 1

Views: 51

Answers (1)

Domain
Domain

Reputation: 11808

Wordpress uses different hooks for dashboard and frontend.

1.If you want to use scripts or style on front end then see following example-

function theme_name_scripts() {
    wp_enqueue_style( 'style-name', get_stylesheet_uri() );
    wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

2.If you want to user script or style on admin side then you need to see following example

function load_custom_wp_admin_style() {
        wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );
        wp_enqueue_style( 'custom_wp_admin_css' );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );

Note - you should use unique name for style-name or script-name.

To know more use following link- https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts

https://codex.wordpress.org/Function_Reference/wp_enqueue_script

Upvotes: 1

Related Questions