How to load default scripts included with WordPress correctly?

I want to know the correct way to load existing scripts in wp-includes/js/jquery/

Example I want to load jQuery UI Tabs

Read More

What I have done for now

function sample_exists_code() {
   echo '<script type="text/javascript" src="'. CONSTANTS_JS .'/jquery.js"></script>'."n"; 
   echo '<script type="text/javascript" src="'. CONSTANTS_JS .'/jquery-ui.js"></script>'."n"; 
}    
add_action('admin_head', 'sample_exists_code');

and this code working fine to load the UI tabs.

But when I try use this code and it’s not working

function sample_exists_code() {
    wp_enqueue_script('jquery');   
    wp_enqueue_script('jquery-ui-tabs');            
}    
add_action('admin_head', 'sample_exists_code');

Let me know the correct way to call the existing scripts.


Update :

// load existings js and template css.
function sample_admin_js_head()
{
    wp_enqueue_script('jquery-ui-tabs', null, array('jquery-ui-core','jquery'), null, false);
    echo '<link rel="stylesheet" type="text/css" href="' . CONSTANTS_STYLES . '/style.css" />' . "n";
}

// load up the menu page
function sample_add_page()
{
    $optionpage = add_theme_page(__('Theme Options'), __('Theme Options'), 'edit_theme_options', 'sample', 'sample_do_template');
    add_action( "admin_print_scripts-$optionpage", 'sample_admin_js_head' );
}

add_action('admin_menu', 'sample_add_page');

Related posts

Leave a Reply

3 comments

  1. Hi @haha:

    'admin_init' is definitely an workable way to load scripts but you might also want to take a look at this blog post and consider using the "admin_print_scripts-{$page}" hook instead which can allow you to only load on your page when you need it and not burden the other admin pages:

    Here’s code from the blog post, albeit modified a bit:

    $your_page = add_management_page('myplugin','myplugin',9,__FILE__,
                   'yourplugin_admin_page');
    add_action("admin_print_scripts-{$your_page}",'yourplugin_jquery_tabs_loader'); 
    function yourplugin_jquery_tabs_loader() {
      // what your plugin needs in its <head>
    }
    
  2. Got it worked 🙂

    function sample_exists_code() {
    wp_enqueue_script('jquery-ui-tabs', null, array('jquery-ui-core', 'jquery'), null, false);     
    }    
    add_action('admin_init', 'sample_exists_code');