简体   繁体   中英

add js to <head> of specific page via functions.php in wordpress

how can I load a specific js based on post ID into the head of the page. I came through wp_register_script and wp_enqueue_script which seems to be fine for external js files, but for inline js, I somehow cannot get it working.

// 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');

You'll want to use the wp_head action to do this and place code outside of PHP. See below for an update of your code:

// 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);

It's used on the websites I use and work fine.

When inserting non-php code such as HTML tags etc. close the php tag with ?> and then use <?php to end HTML code.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM