0

我在 WordPress 中遇到了一件奇怪的事情wp_enqueue_script(),我想要发生的是通过向 functions.php 添加一个动作挂钩来在页面上添加一个脚本但是当我这样做时,它不会在页面上添加脚本但是当我把代码作为一个插件,它现在在页面上添加脚本

注意:在functions.php中,当我在页脚中添加脚本时:add_action('wp_footer','function_name');它工作正常但是当我将它添加到wp_head和init时,当我将代码放在时它不会添加脚本functions.php,但是当我这样做时它可以完美运行即使我在 wp_head 和 init 上添加它作为插件

我需要在初始化或 WP_HEAD 上添加脚本,但是当我将代码放在 FUNCTIONS.PHP 上时它不起作用。我需要脚本成为主题的一部分,而不是作为插件

//functions.php
add_action('init', 'function_name');

function function_name(){
wp_enqueue_script( 'script_holder', get_template_directory_uri() . '/script.js');   
}

//as a plugin
add_action('init', 'function_name');

function function_name() {
    $plugin_location=WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));
    if( !is_admin()){
        wp_enqueue_script( 'script_holder', $plugin_location . '/script.js');
    }
}

我知道它甚至应该在functions.php中工作,但我真的想知道为什么会发生这种情况,谁能帮助我并向我解释为什么会发生这种情况,好吗?

非常感谢您

基本上这正是我正在做的:

add_action('init', 'override_jquery');

function override_jquery() {
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_enqueue_script( 'nashgraphics_jquery_library', get_template_directory_uri() . '/bootstrap/js/jquery-1.9.0.min.js');
    }
}
4

2 回答 2

2

There can be several things going on, But since the problem occurs only with functions.php , One would think this is theme related . You should be sure that the theme has both :

wp_head() – ( immediately before </head> )

And

wp_footer() – ( immediately before closing </body> )

If the theme author did not included both , or if the theme is missing even ONE of those functions , scripts might fail to load. ( and 80% of the plugins will have issues ) .

Also, you did not specify which theme you use (your own code ?? ) and if it is a child theme or not .

You are using get_template_directory_uri() which can not be overriden by child themes , I do not know if this is a part of the problem, but you might want to also try using , get_stylesheet_directory_uri() which in many cases is the better choice .

Seeing your update :

It is a very bad practice to replace the core jQuery with another one withpout a fallback. Anyhow ,you ca try dropping the !is_admin() condition, or alternatively log out and watch your sites code . ( I have a feeling that you are debugging it while logged in and with the wp admin bar on .. )

于 2013-04-29T06:25:56.583 回答
1

在前端排队脚本的正确钩子是wp_enqueue_scriptshttp ://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts

于 2013-04-28T22:06:34.450 回答