Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress WordPress Hooks - Actions and Filters Hooking Into WordPress Plugins Gravity Forms Example

Where to write the hooks?

In the WP Hooks course Zac shows an example with Gravity Forms and I'm just wondering where would you write the hooks? Does it all go into functions.php?

2 Answers

It depends on what theme you are using. Most themes have an inc folder that are included into the functions.php file. In the inc folder there is generally an extras.php file, in there is where I write my custom hooks. It also depends on how manny hooks you are using, if it's like 1-3 I think in the functions.php is fine, but more I would suggest putting into a separate file and include it into the functions.php file. If you want you can have a file called hooks.php and put your custom hooks into that file. It's really up to you, the main thing is to not clutter the functions.php file.

Sue Dough
Sue Dough
35,800 Points

You write the action hook either below or above the function. Stick with one way. I prefer it above the function so I can easily see. The functions.php is a good place for a theme. You can also use action hooks in plugin files etc as long as it gets loaded by WordPress. If you want to hook to an external plugin then its best practice to create your own plugin to hook. You can get away with hooking to the external plugin in your functions.php but if you deactivate the plugin that function is still being called so it may be good to wrap it with an if conditional and function_exists ( google or duckduckgo it ).

I posted an example functions.php hook below. hello_friend is the name of the function. publish_post is the action hook so when a post is published this hook will run.

<?php

add_action( 'publish_post', 'hello_friend' );

function hello_friend {
  // do whatever you want here
  return "Hello Friend.";
}

Can also be written below the function like this

<?php

function hello_friend {
  // do whatever you want here
  return "Hello Friend.";
}

add_action( 'publish_post', 'hello_friend' );

You could even have all your functions and the action hooks for all of them at the bottom of the file. This would be horrible to manage but I am trying to make the point it does not matter where the action hook is a long is as long as it can call the function.