My function doesn’t work into WordPress but outside, it works – what am I missing?

WordPress template files are included via functions, which places the scope of those included files within those functions. That’s why you have to declare it global twice. Here is an example you can try with 3 simple php files to illustrate this without using WordPress:

main.php

function include_file_1(){
    include '1.php';
}
function include_file_2(){
    include '2.php';
}
include_file_1();
include_file_2();

1.php

function tester(){
    global $pol;
    $pol="ok all fine and working";
}

2.php

tester();
echo $pol;

If you test this out, you will see you get nothing from echo $pol, it’s not within scope. Now edit 2.php to declare global $pol first:

global $pol
tester();
echo $pol;

And now you get the expected results.

Leave a Comment

error code: 523