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?
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