【问题标题】:Run Specific Js on Specific page Wordpress在特定页面 Wordpress 上运行特定 Js
【发布时间】:2017-09-03 02:03:02
【问题描述】:

我想在特定页面上运行特定的 js。即:www.custom.com/english/

我已经尝试了以下两个代码(header.php 和 functions.php),但它们都不起作用。

代码 1:

<script>
if(location.pathname=="/english/") 
 script.src = /js/custom.js;
</script>

代码 2:

function my_scripts() {
    if( is_page( array( 'about-us', 'contact', 'management' ) ){
        wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
    }
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );

标题一根本不显示,也没有错误。 functions.php 是语法错误。

有什么建议吗? 非常感谢

PS:我正在使用 WordPress。

【问题讨论】:

    标签: javascript wordpress url


    【解决方案1】:

    你的代码很棒!您只是缺少一个右括号:

    function my_scripts() {
        if( is_page( array( 'about-us', 'contact', 'management' ) ) ){
            wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
        }
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts' );
    

    为了将来参考,在你的 wp-config.php 文件中你可以将 debug 设置为 true,我相信这会得到它。

    【讨论】:

    • 哦哇没有注意到右括号哈哈!顺便说一句,有没有一种快速的说法。如果 url 包含某些内容,则加载此脚本?即:if( is_page( array( about-us/test/ )
    • 哈哈,发生了!是的,它称为 URL 参数,请参见:stackoverflow.com/questions/4586835/… :) 然后您可以在 if 页面中运行另一个 if 语句来检查 url 参数是否存在,然后记录代码。我希望这会有所帮助。
    • 我在覆盖部分遇到了一些问题,因为我的主要目标是为 frontpage 运行一个脚本并为 frontpage/test/ 运行另一个脚本 - “/test/”是来自weglot 插件(翻译)。我的问题是它一直在加载第一个脚本,因为它在 url 中有“frontpage”并且它不是一个单独的页面。所以它不会加载另一个,因为它“认为”它是同一个页面(它也有点像,但翻译版本)
    • 嗨,这可能会有所帮助pastebin.com/YQ1Xhd9Q 它来自这里,developer.wordpress.org/reference/functions/is_page 似乎使用此代码您可以测试子页面!希望它有效
    【解决方案2】:

    还有多种其他方式。

    只需打开你的 header.php 并尝试获取当前页面的 slug 或 id 并输入简单的 if 条件它肯定会包含你的 js

    代码 1

    global $post;
    $post_slug=$post->post_name;
    if($post_slug == 'about'){
    <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
    }
    

    或代码 2

    $currentID= get_the_ID();
    //instead of 10 put the your id
    if($currentID == 10){
     <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
    }
    

    【讨论】:

    • 虽然此答案可行,但通常建议使用 wp_enqueue_script 将 js 文件包含在 Wordpress 中,以便它们可以正确排队。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    相关资源
    最近更新 更多