【问题标题】:Wordpress add javascript in footerWordpress 在页脚中添加 javascript
【发布时间】:2015-06-20 19:43:34
【问题描述】:

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

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

在家功能正常,但是当访问一个页面子时,由于搜索目录,他没有找到:

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

我看到我必须使用:

 wp_enqueue_script ()

但是我应该把这段代码放在哪里?

谢谢

【问题讨论】:

    标签: javascript php wordpress


    【解决方案1】:

    您只需要在您的网址之前添加一个“/”,以便从根目录启动它:

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

    确实在主页上它会查找 yoursite.com/wp-content 但在其他页面上它会搜索 yoursite.com/current-page/wp-content 并且显然会导致 404。

    添加/使其始终查找 yoursite.com/wp-content

    【讨论】:

    • 以这种方式访问​​本地主机而不是本地主机/项目
    • @Daniel 确实,但我想让他明白为什么它不起作用,那么它只是适应。考虑到他使用wordpress,更好的答案是使用wordpress custom url
    【解决方案2】:

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

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

    您需要将此添加到主题目录wp-content\themes\your_theme\footer.php 中的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 模板文件中创建一个方法,然后使用加载您的脚本

    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    

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

    结帐wp_enqueue_script 了解更多信息。

    【讨论】:

    • 我在哪个文件中注册wp_register_script?如何将我的 js 我的 pc 文件上传到 wordpress?
    • 在此处复制您的主题项目中的 JS 文件:wp-content\themes\your_theme\js 然后转到wp-content\themes\your_theme\footer.php 并添加:&lt;script src="&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/js/script.js"&gt;&lt;/script&gt; 要使用wp_register_script,请将其添加到wp-content\themes\your_theme\functions.php,如果文件没有'不存在创建它,它会自动加载..
    • 这里有一个如何使用它的例子: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' );
    【解决方案3】:

    由于你好像用的是WordPress,所以可以替换

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

    与:

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

    【讨论】:

    • 能否请您检查执行此更改后生成的源代码并报告此&lt;script&gt; 块的输出是什么?
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2011-02-17
    • 2019-02-03
    相关资源
    最近更新 更多