我在 StackOverflow 和其他网站上看到了很多关于为什么“wp_enqueue_scripts”不起作用的问题,但没有一个是我想要的。
我想将脚本导入到我的 Wordpress 主题中,并且我复制了从主要开发人员 Wordpress 网站上截取的一个代码。
我的“functions.php”中有以下代码,输出为“OUTPUT 1OUTPUT 4”。似乎 'wpdocs_theme_name_scripts()' 永远不会被调用。
/**
* Proper way to enqueue scripts and styles.
*/
function wpdocs_theme_name_scripts() {
echo "OUTPUT 2";
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true );
echo "OUTPUT 3";
}
echo "OUTPUT 1";
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
echo "OUTPUT 4";
Run Code Online (Sandbox Code Playgroud)
请注意,wpdocs_theme_name_scripts()不会在之后echo "OUTPUT 1";和之前调用echo "OUTPUT 4";
add_action()只会注册一个回调,遇到时会运行wp_head()。您可以在此答案中找到有关此内容的更多详细信息。
你添加wp_head()主题了吗?它通常添加在标签header.php之前</head>,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title(); ?></title>
<?php wp_head(); ?>
</head>
Run Code Online (Sandbox Code Playgroud)