1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Wordpress Tutorial- How to add javascript dependent on jquery in wordpress

Discussion in 'Content Management' started by vikaskumarbhardwaj, Jun 29, 2013.

  1. #1
    Hi, I recently started to visit this forum and i found a lot of people are struggling just for basic WordPress features to embed in their site. So i thought that i should start a tutorial series for WordPress newbies.

    My first tutorial will be how to add scripts, JavaScript and inbuilt jQuery plugins into your WordPress theme or plugin.

    First how wordpress calls script to header or footer in frontend or backend.
    WordPress uses wp_enqueue_scripts hook to add your custom scripts to header or footer of site.
    add_action('wp_enqueue_scripts','load_javascripts');
    function load_javascripts(){
    wp_enqueue_script('test','URL To script',array('jquery'),3.0,false);
    }
    PHP:
    Now lets explain this.

    The first hook wp_enqueue_scripts will call load_javascript function and this function will call an another function called wp_enqueue_script.

    You can also register script to wordpress and use it when you want.
      wp_register_script('donut_chart', 'URL to file',array('jquery'),3.0,false);
    
    PHP:
    Both wp_enqueue_scripts and wp_register_script have same parameters.
    This has five parameters
    1. The first is the name of script/js
    2. Second parameter is URL to script
    3. Third is dependency- if your javascript is dependent on any script and you want to load that script before current script then you should put that name in array. In this instance i have added jquery. You can pass other dependency also in same array.
    4. Fourth parameter is the version of your script.
    5. And last one- loads your js in footer or in header. Set false to load in header and true to load in footer.
    If you don't want to add a dependent js file but just a js variable in header then use this code.
        wp_localize_script( 'star_rating', 'post_ajax_star', admin_url( 'admin-ajax.php' ));
    PHP:
    But before using this you must have to register your script to wordpress. In this case your registered script name is star_rating.

    Now for using jQuery you can't use $ sign in front of jQuery functions so you must have to add jQuery every time.
    Or as i do just pass $ in ready function of jquery and then you can use $ sign.
    for example
    jQuery(document).ready(function($){
     
    })
    Code (markup):
    If you have any query then feel free to ask me. I will try to help you as much i can.
    Thanks
     
    vikaskumarbhardwaj, Jun 29, 2013 IP
    Devtard likes this.