WP_REGISTER_SCRIPT(...$in_footer=TRUE)不起作用

时间:2016-05-30 作者:RubenGeert

我想在我的页脚中加载一些javascript文件。我试着在functions.php 像这样:

function my_init() {
        // LOAD JQUERY
        wp_deregister_script(\'jquery\');
        wp_register_script(\'jquery\', \'//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\',$deps = array(),$in_footer = true);
        wp_enqueue_script(\'jquery\');

        // LOAD STUTS
        wp_register_script(\'stuts\',get_bloginfo(\'template_url\') . \'/js/spss-tutorials-custom-functions.js\',$deps = array(\'jquery\'),$in_footer = true);
        wp_enqueue_script(\'stuts\');

        // CONDITIONALLY LOAD MATHJAX
        wp_register_script(\'mathjax\',\'//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML\',$deps = array(),$in_footer = true);
        $url = explode(\'?\', \'http://\'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
        $ID = url_to_postid($url[0]);
        $mathjax = get_post_meta($ID,\'mathjax\',true);
            if($mathjax == \'y\'){
                wp_enqueue_script(\'mathjax\');
            }
}

add_action(\'init\', \'my_init\');
但是,所有脚本仍在我的标题中加载。

我尝试了解决方案here, herehere 但他们没有解决问题。

我有

<?php wp_footer(); ?>
</body>
在我的footer.php 文件有什么建议吗?

1 个回复
SO网友:kaiser

首先,在(渲染)时间中选择正确的位置init, 当您想在上添加回拨时wp_enqueue_script.

示例:

add_action( \'wp_enqueue_script\', function() {
    wp_deregister_script( \'jquery\' );
    // Rest of logic
} );
同时,您可能希望使用core使用的正确版本。我知道,经常关注这一点很麻烦,没有人想监控资产/依赖关系。幸运的是,您可以使用core中已经存在的信息。资产所需的依赖关系也是如此。示例:

add_action( \'wp_enqueue_script\', function() {

    $version      = $GLOBALS[\'wp_scripts\']->registered[\'jquery\']->ver;
    $protocol     = \'sprintf( \'http%s://\', is_ssl() ? \'s\' : \'\' );
    $dependencies = $GLOBALS[\'wp_scripts\']->registered[\'jquery\']->deps;

    wp_enqueue_script( 
        \'jquery\',
        "{$protocol}cdn.example.com", 
        $dependencies,
        $version,
        TRUE
    );
} );
将已注册的脚本移动到页脚还有一种更简单的方法可以将已注册的脚本移动到页脚:直接在脚本注册表中编辑它的信息。考虑以下(MU)插件:

<?php
/* Plugin Name: Moves registered scripts to the footer */
add_action( \'wp_enqueue_scripts\', function() {
    foreach ( apply_filters( \'wp_scripts.footer\', [] as $script )
        $GLOBALS[\'wp_scripts\']->add_data( $script, \'group\', 1 );
}, PHP_INT_MAX -1 );
现在,您只需将数组附加到上面的过滤器并将脚本移动到页脚:

add_filter( \'wp_scripts.footer\', function( Array $scripts ) {
    return [ 
        \'jquery\', 
        # Other scripts
    ];
} );
其他注意事项,我无法留下来写下…

关于您的代码,还有许多非常奇怪(但有效)的地方需要注意:

当您不需要变量时,您正在分配变量。特别是在函数调用中,不需要使用myFunction( $var = \'foo\' ). 只需添加值即可//url.tld/script.js, 然后,客户端将能够决定要走的路线:HTTPS vs HTTP。这对于分布式代码来说可能还可以(即使这样,最好先获取协议并使用它),但如果您知道您为站点提供服务的方式,那么请直接使用它。它速度更快,如果有HTTPS可用,那么看在上帝的份上:使用它$_SERVER 仅当脚本始终只能通过客户端执行时才可以。在命令行上,使用此阵列中的数据是不可靠的。在某些情况下,它会发生变化,而在另一些情况下,它不会设置。WP有一些可供您使用的后备方法