简体   繁体   中英

Including jQuery in Wordpress-Plugin

I'm using jQuery/ajax in my Wordpress-Plugin. When I link jQuery this way, it even works

add_action('wp_head', 'hook_files');


function hook_files()
{
    $output = "
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
<script src='//code.jquery.com/ui/1.11.2/jquery-ui.js'></script>
<link rel='stylesheet' href='//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css'> ";

    echo $output;    
}

But I know that this is not the right way to do. So I looked up the documentation and implemented this:

function enqueue_my_scripts()
{
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'jquery-ui-core' );
}
add_action('wp_enqueue_scripts', 'enqueue_my_scripts');

But then it doesn't work anymore... Is there something wrong?

Thanks!

I would recommend using the enqueue to load the script, especially jquery, so you could just fire it like so: [Recommended Solution]

wp_enqueue_script('jquery');

Or a more elobrate approach:

function my_scripts() {
wp_enqueue_script( 'jquery' );
wp_register_style( 'prefix-style', plugins_url('mystyle.css', __FILE__) );
wp_enqueue_style( 'prefix-style' );
}
add_action('wp_enqueue_scripts','my_scripts');

Unless you want to use a cdn or a google repo for jquery, then i would recommend doing the following:

wp_enqueue_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js', array('jquery'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM