I'm totally new in WordPress as well as in PHP and making my first application with it.

Currently, I use 'HTML block Element' to add content with custom HTML and inline Javascript code on blank WordPress pages (using Elementor). I want to create a new config file(or add data on an existing one) on which I can define some variables which I then will be getting using Js and work accordingly.

I tried adding defines in the wp-config file and accessing them with Js but it didn't work.


define('PERSONAL_KEY', 'VALUE');

In custom HTML code element of WP Page

   var data = "<?php echo PERSONAL_KEY; ?>";
   // Didn't worked

Is there any way to achieve getting variables inside inline JS code from an external config file?

1 Answer 1


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

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
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
            'personalKey' => defined('PERSONAL_KEY') ? PERSONAL_KEY : '',
            // 'more' => 'values',

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

// assets/scripts.js
  • 1
    Thankyou I did the same and it worked for me. I only had to create a separate blank js file to include to that particular page.
    – aditya
    Commented Apr 17, 2021 at 19:22
  • I now face another problem. I want to store security keys also. These are used inside the Inline JS of these HTML block elements. Using this method anyone can access those variables using console. How can I achieve more security in this? Can you please help me in this?
    – aditya
    Commented Apr 17, 2021 at 19:23
  • @aditya Yes, if you use this method to add security keys to your site, then anyone inspecting the source code could see them. I'm not much of a security expert. You shouldnpost that as another question so that other members of the WPSE can chime in. Commented Apr 17, 2021 at 20:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.