php - 如何使用 wp_enqueue_script?

标签 php javascript wordpress wordpress-theming

好的,所以这是在我的functions.php文件中:(以下是利用下面酷的答案的编辑版本。之后我将保留原始版本:

function mdg_setup_scripts() {
  wp_register_script( 'hoverIntent', get_bloginfo('template_url').'/js-custom/hoverIntent.js', array( 'jquery' ));
  wp_enqueue_script( 'hoverIntent' );
  wp_register_script( 'mdMenuAnimation', get_bloginfo('template_url').'/js-custom/mdMenuAnimation.js', array( 'jquery' ));
  wp_enqueue_script( 'mdMenuAnimation' );
}
add_action( 'wp_enqueue_scripts', 'mdg_setup_scripts' );

这是我最初拥有的:

function mdg_setup_scripts() {
  wp_register_script( 'hoverIntent',
    get_bloginfo( 'template_url' ) . '/js/hoverIntent.js',
    array( 'jquery' ),
    false,
    true );
  wp_register_script( 'mdMenuAnimation',
    get_bloginfo('template_url') . '/js/mdMenuAnimation.js',
    array( 'jquery', 'hoverIntent' ),
    false,
    false );
  if (!is_admin()) {
    wp_enqueue_script( 'mdMenuAnimation' );
  }
}
add_action( 'init', 'mdg_setup_scripts' );

js 文件存在于指定的文件夹中。 但前端根本没有加载 JavaScript。 我做错了什么,但是什么? 我需要注册jquery吗(不过我以为WP里有jquery)? 我需要分离入队调用吗?我需要在 header.php 中添加一些内容吗?

最佳答案

你不需要添加jquery。如果未添加,并且您的自定义脚本依赖于它(就像您在代码中编写的那样),它将由 wordpress 添加。 这段代码可以工作(我刚刚测试过)但是..

而不是这个:

if (!is_admin()) {
    wp_enqueue_script( 'mdMenuAnimation' );
}

wordpress 建议您使用钩子(Hook):

Wordpress-codex: Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side.

所以它应该是这样的:

function my_scripts_method() {
   wp_register_script( 'somehover', get_bloginfo('template_url').'/js-custom/hoverIntent.js', array( 'jquery' ));
   wp_enqueue_script( 'somehover' );
}  

add_action('wp_enqueue_scripts', 'my_scripts_method');

Wordpress-codex: by using the wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.

关于php - 如何使用 wp_enqueue_script?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10762908/

相关文章:

php - jQuery 发布到 php 文件

javascript - Google Calendar API 权限不足

wordpress - 如何在 Wordpress 中创建指向本地网络服务器上的文件的链接

用于 Wordpress Customizr 主题导航悬停动画的 CSS

html - 如果按钮(或 div)不适合屏幕分辨率,请将它们一个放在另一个下方

没有 "dot"运算符的 PHP 字符串连接

php - 如何设置文本输入字段(html/php)的要求?

PHP: MYSQL select inside another MYSQL select?

php - 使用 LIMIT 和 UNION 选择查询 - 性能问题

javascript - react 路由器位置不匹配任何路线