0

I have a pretty simple problem (I think) which I can't find an answer to. The setup is pretty basic. I have a function which is in functions.php:

function function_A($variable)
{
    return $variable + 1;
}

In another php file I can call this function like this which works as expected:

   require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');
   $result = function_A(5);

In a totally separate .php file I got lots of functions within <script> tags, and in one of them I want to access function_A from functions.php. Like this:

<script>
function problem_function(){
    // Here I want to call function_A and get the variable back to use in JS
}
</script>

I tried something like this which made the page fail to load:

<script>
function problem_function(){
    <?php
        require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');
        $result = function_A(5);
    ?>
   
    var test = <?php echo $result; ?>;
}
</script>

How can I access function_A from a function within the <script> tag?

5
  • Is the $variable you want to pass to your PHP function a dynamic JS value? If so, then you'll need to use Ajax. If not, you can just use <?php function_A(1); ?> inside your JS function.
    – DeltaG
    Aug 2 at 9:56
  • bootstrapping WordPress in standalone files via wp-load.php can be dangerous and fragile, and should be avoided. If you need to make AJAX requests to your site or handle forms you should do that using WordPress, not direct requests to custom PHP files
    – Tom J Nowell
    Aug 2 at 9:58
  • @TomJNowell, if there is a better way of calling a function in function.php from another .php file I am all open to ideas, I just took a solution from SO that worked. Do you have a better solution? Keep in mind I am a beginner wordpress developer..
    – eligolf
    Aug 2 at 10:44
  • Update, it worked to remove the wp-load code without any other changes. However, calling functionA from functions.php is still not working from the <script> tags in the other php file
    – eligolf
    Aug 2 at 10:54
  • you have to use AJAX, PHP runs on the server in a data centre, javascript runs in the browser on the machine in front of you. If you want to run code on the server you got to make another brand new request complete with everything it needs to know to do its thing. Think of it this way, if you ask me to send you a package and it arrives, but you forgot something, it doesn't just appear, you've got to email me and ask for the thing you forgot or make a brand new purchase, that I can then process as a new follow up request. I'll also need info like who you are and your order to process it
    – Tom J Nowell
    Aug 2 at 15:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.