2015-06-19 72 views
2

我需要在站点页脚中添加一个脚本。 我只是引用footer.php:Wordpress在页脚中添加javascript

<script src="wp-content/file/script.js"></ script>

在家工作正常,但是当访问一个页面的孩子,他没有找到,因为搜索的目录:

site/page-child/wp-content/file/script.js

我看到了,我必须使用:

wp_enqueue_script()

但我应该在哪里把这个代码?

感谢的

回答

0

因为你似乎使用WordPress,你可以替换

<script src="wp-content/file/script.js"></ script> 

有:

<script src="<?php site_url('/wp-content/file/script.js'); ?>"></script> 
+0

它没有工作 – Daniel

+0

请您检查执行此更改后产生的源代码并报告此块的输出是什么? –

1

你只需要添加一个 “/” 为了您的网址前从根启动它:

<script src="/wp-content/file/script.js"></ script> 

确实在主页上它寻找yoursite.com/wp-content,但在其他页面上它搜索yoursite.com/current-page/wp-content,显然它在404结果。

添加/使它总是看对于yoursite.com/wp-content

+0

通过这种方式,它访问本地主机,而不是localhost/project – Daniel

+0

@Daniel的确,但我想让他明白为什么它不起作用,那么它只是适应。考虑到他使用wordpress,更好的答案是使用wordpress自定义url –

1

添加<script src="wp-content/file/script.js"></ script>不是一个干净的方式来加载您的JS文件,因为这不是一个相对的URL,当您激活您的子主题可能您的主题不会加载您的JS文件,解决方案是:

<script src="<?php echo get_stylesheet_directory_uri(); ?>/js/script.js"></script> 

您需要这在你的主题直销添加到您的footer.php文件保守党wp-content\themes\your_theme\footer.php

但最好的方法是使用WP挂钩,包括脚本,首先你需要使用注册它们

wp_register_script('my_script_name', get_template_directory_uri(). '/js/script.js'); 

然后只需加载它们

wp_enqueue_script('my_script_name'); 

不要试图注册并将脚本直接排入footer.php文件,而是在您的functions.php模板文件中创建一个方法,然后使用

加载脚本

注意:要将脚本排入页脚,需要将$in_footer参数设置为true。

结帐wp_enqueue_script欲了解更多信息。

+0

在哪个文件中我注册了 'wp_register_script'? 如何将我的js电脑文件上传到wordpress? – Daniel

+0

将您的JS文件复制到您的主题项目中:'wp-content \ themes \ your_theme \ js'然后转到'wp-content \ themes \ your_theme \ footer.php'并添加: '' 如果文件不存在,使用'wp_register_script'将它添加到'wp-content \ themes \ your_theme \ functions.php'创建它,它会自动加载.. –

+0

这里是一个如何使用这个例子: 'function load_my_script(){ wp_register_script('my_script_name',get_template_directory_uri()。'/js/script.js'); wp_enqueue_script('my_script_name'); } add_action('wp_enqueue_scripts','my_scripts_method');' –