Support » Developing with WordPress » Calling a function from functions.php

  • Resolved bashibazouk

    (@bashibazouk)


    Hi, I am wanting to add an onclick=”myFunction()” function to a button in header.php

    Where is the correct placement for the function? I’ve added it in functions.php:

    function myFunction() {
        console.log("myFunction");
    }
    add_action('wp_footer', 'myFunction');

    But I get the error:

    myFunction is not defined

    Any clues? Thanks!

Viewing 7 replies - 1 through 7 (of 7 total)
  • You are not rendering the function itself. It is actually rendering its output i.e. console.log.

    You have to either render the actual js functon through the php funtion you hooked into wp_footer action or you can ditectly write the function into your footer.php.

    I hope this will help.

    Thanks for your reply. Is that the WordPress best practice method of calling functions then? Seems a bit elongated

    In footer.php

    
    <script type="text/javascript">
    	function myFunction() {
    		console.log("myFunction");
    	}
    <script>
    
    Moderator bcworkz

    (@bcworkz)

    The WP “best practice” is even more elongated than that! We are asked to enqueue JS code through wp_enqueue_script(). TBH, this is much too convoluted for simple JS. What Subrata suggests is adequate for simple JS.

    You seem to have JS and PHP mixed up and confused. While there is some intersection in getting one to cause the other to happen, they are basically two separate entities operating in two different environments. JS runs in the visitor’s browser and has limited access to resources on your server. PHP runs on your server, has full access to server resources, but has limited access to browser resources.

    You can use the “wp_footer” action in PHP to output a JS function declaration like so:

    function my_php_function() {
      echo '<script>
        function myFunction() {
          console.log("myFunction() was called.");
        }
      </script>';
    }
    add_action('wp_footer', 'my_php_function');

    @bcworkz you are completely correct, I confused PHP with JS!

    I found the best way is to have external script in the footer as @wpgear suggested

    Thanks for your help

    Please change the status to resolved if you are satisfied. Thank you!

    Solved, thanks

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Calling a function from functions.php’ is closed to new replies.