For debug purposes in further development, I am trying to add a simple function to a WordPress site and execute it in the Firefox console.
As in https://developer.wordpress.org/reference/functions/add_action/, I put into functions.php
of my OceanWP theme:
add_action( 'hello_world', 'hdt_hello_world' );
function hdt_hello_world($text) {
echo 'Hello World!';
echo $text;
}
Reload the page and try to execute from Firefox Console, getting:
hello_world('Hi!');
Uncaught ReferenceError: hello_world is not defined
<anonymous> debugger eval code:1
Seems I miss the point somewhere... Could you give a hint?
The hint by Hamid Reza Yazdani helped to clarify: I basically tried to call a PHP function in browser console - it's not intended to work - and will not work - this way.
The (hopfully) proper way is to create a JavaScript function and enqueue it using a WordPress hook.
assets/js
folder of the WP theme, create a file, e.g. my_functions.js
, with the following code:function my_hello_world(text) {
console.log("Hello world!");
console.log(text);
}
functions.php
file of the theme (not update-safe!), add:function my_functions_enqueue_script() {
wp_enqueue_script( 'my_functions', get_template_directory_uri() . '/assets/js/my_functions.js', array ( 'jquery' ), 0.1, true);
}
add_action('wp_enqueue_scripts', 'my_functions_enqueue_script');
The execution of my_hello_world('Hi!');
in browser console then yields the desired console output.
For more details, see:
If server-side PHP execution (esp. AJAX) is needed, a more complex interaction between JS and PHP code needs to be implemented 'the WordPress way'; one may look at: