动态地将脚本添加到某些页面

时间:2014-04-29 05:10:39

标签: javascript wordpress

我有一个明显受模板驱动的Wordpress网站。如果我想在特定页面上加载脚本,我需要添加什么JavaScript?最好由URL定义(除非有更好的方法?)。

IE:仅在URL =“abc.net/123”

时加载脚本

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

if (window.location.href.indexOf('abc.net/123') != -1) {
  document.write('<script src="foo.js"><\/script>');
}

这样只有在该位置包含“abc.net/123”时才会添加脚本元素。

但是,如果您控制服务器,那么在那里包含脚本会好得多。

答案 1 :(得分:0)

  

wp_enqueue_scripts是将项目排入队列时使用的正确挂钩   意在出现在前端。尽管名称,它用于   排队脚本和样式。

WordPress中,您可以使用wp_enqueue_script功能动态添加任何scriptfront endwp_enqueue_scripts挂钩。例如:

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script', // script identifier
        get_stylesheet_directory_uri() . '/js/custom_script.js', // path
        array( 'jquery' ) // dependency
    );
}

// Register the handler
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

要检测某个页面(页面/帖子),WordPress中有许多可用的功能,但url abc.com/123似乎没有资格使用这些功能({1} 1}},is_home()等)或者我不确定这是什么页面所以我会使用这样的东西:

is_single()

因此,请将此代码粘贴到主题的$Page = $_SERVER['REQUEST_URI']; if ($page == 123) { // or '123' and only REQUEST_URI //add script } 文件中:

functions.php

阅读答案中提供的链接以获取更多信息。