【问题标题】:wp_enqueue_scripts not being calledwp_enqueue_scripts 没有被调用
【发布时间】:2017-01-04 02:18:31
【问题描述】:

我在 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";

【问题讨论】:

  • 当您将wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true ); 替换为wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/main.js'); 时,您是否看到任何变化?

标签: php wordpress


【解决方案1】:

对于在 admin 页面中遇到此问题的任何人,请使用 admin_enqueue_scripts 挂钩而不是 wp_enqueue_scripts 挂钩。

Documentation here.

【讨论】:

    【解决方案2】:

    注意wpdocs_theme_name_scripts() 不会在echo "OUTPUT 1"; 之后和echo "OUTPUT 4"; 之前被调用

    add_action() 只会注册一个在遇到wp_head() 时运行的回调。你可以在this answer找到更多细节。

    您是否在主题中添加了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>
    

    【讨论】:

    • 哦,非常感谢您在添加 &lt;?php wp_head(); ?&gt; 之后一切正常
    【解决方案3】:
        <?php
         /* This code is use in function.php */
        add_action( 'wp_enqueue_scripts', 'mytheme_scripts' );
    
        function mytheme_scripts() {
        echo "Helllo";
        wp_enqueue_style( 'mytheme-owlcaroselcss', get_template_directory_uri() . '/css/owl.carousel.css', array( 'mytheme-style' ), '20150312' );
           echo "Helllo1";
        }
       /* ****** */
         ?>
         use in header.php with wp_head() function
        <html>
        <head>
         <?php wp_head();?>
        </head>
        </html>
    

    【讨论】:

    • 没有任何区别,我添加调试'echo'输出仍然相同。 mytheme_scripts() 甚至没有被调用
    • 请解释一下你的答案
    猜你喜欢
    • 2017-10-07
    • 2015-12-06
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2019-03-31
    • 2012-12-16
    相关资源
    最近更新 更多