How to create a custom config file and get data using inline JS in a wordpress page

I suspect that the html block element you’re using doesn’t handle php, which is why the script tag isn’t working the way you hope.

wp_localize_script() is a handy function to pass data from PHP to scripts. The function basically does the same thing you were trying to do with the html block.

Lets say you’re doing this in your theme and you have the following structure,

// theme structure
/your-theme
    style.css
    functions.php
    /assets
        scripts.js

And you have you have defined a constant in the wp-config.php file.

// wp-config.php
define('PERSONAL_KEY', 'VALUE');

In your theme functions.php file you can then enqueue your scripts file, where you need the defined constant, and use the wp_localize_script().

// functions.php
<?php
add_action('wp_enqueue_scripts', 'your_theme_assets');
function your_theme_assets() {
    $url = get_template_directory_uri();
    // enqueue scripts
    wp_enqueue_script( 'your-theme', $url . '/assets/scripts.js', array(''), '1.0.0', true );
    // localize variable for scripts
    wp_localize_script(
        'your-theme', 
        'yourTheme', 
        array(
            'personalKey' => defined('PERSONAL_KEY') ? PERSONAL_KEY : '',
            // 'more' => 'values',
        )
    );
}

After this, you can access the personalKey from the localized yourTheme global variable.

// assets/scripts.js
console.log(yourTheme.personalKey);

Leave a Comment

tech