php – Make a variable global and use it for inline script


We got two simple functions that have Javascript as a string variable inside them.

function script_one(){
  // do something...
  $script .= 'console.log("script one run")';

function script_two(){
  // do something...
  $script .= 'console.log("script two run")';

This $script variable of course is not accessible out of the functions so the function below will not work:

function enq_scripts() {
  wp_register_script( 'elements-script', '', array("jquery"), '', true );
  wp_enqueue_script( 'elements-script' );
  wp_add_inline_script( 'elements-script', $script);
add_action('wp_enqueue_scripts', 'enq_scripts');

Even if we add to the two functions something like global $script, it will still not work. I even tried with $GLOBALS but also didn’t work, I think because I am using PHP 8.1

How could I make the $script variables to be able to get updates through .= but also be accessible inside the wp_enqueue_scripts action?

dominotrix 2 months 2022-12-02T07:22:10-05:00 0 Answers 0 views 0

Leave an answer