1

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

1 Answer 1

2

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"; ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.