通过WordPress中的functions.php将js添加到特定页面

时间:2018-11-17 14:42:32

标签: php wordpress

如何将基于帖子ID的特定js加载到页面顶部。我遇到了 wp_register_script wp_enqueue_script ,这对于外部js文件似乎很好,但是对于内联js,我却无法以某种方式工作。

// call the function that adds your current script 
function customjs_load()
{
    if (is_page(197))
    {
        wp_register_script( 'rechner', 

        <script type="text/javascript">
        var _cmr = {
            opti_pid: "partnernname",
            opti_purl: "domain.com",
            ga_medium: "affiliate",
            ga_campaign: "link",
            title_tab1: "Kreditrate berechnen",
            title_tab2: "Finanzierungssumme berechnen",
            maxwidth: "1200px",
            tab: "no" //1, 2, no
        }
        </script>

        <script src="https://www.url.com/rechner/calc.js" type="text/javascript"></script>

        ); // register your script 
        wp_enqueue_script( 'rechner' ); // enqueue it to be added in the head section
    }
}

add_action('get_header', 'customjs_load');

1 个答案:

答案 0 :(得分:0)

您将需要使用wp_head操作来将代码放置在PHP之外。请参见下面的代码更新:

// call the function that adds your current script 
function customjs_load()
{
    if (is_page(197))
    {

    ?>

        <script type="text/javascript">
        var _cmr = {
            opti_pid: "partnernname",
            opti_purl: "domain.com",
            ga_medium: "affiliate",
            ga_campaign: "link",
            title_tab1: "Kreditrate berechnen",
            title_tab2: "Finanzierungssumme berechnen",
            maxwidth: "1200px",
            tab: "no" //1, 2, no
        }
        </script>

        <script src="https://www.url.com/rechner/calc.js" type="text/javascript"></script>

    <?php

    }
}

add_action('wp_head', 'customjs_load', 2);

已在我使用且正常工作的网站上使用。

在插入非PHP代码(例如HTML标签等)时,请使用?>关闭php标签,然后使用<?php结束HTML代码。

示例:

<?php $somevar = "hi"; ?> HTML content <?php $another = "done"; ?>