WordPress Tutorials

If you want to “hook” a function into another function in WordPress, add_action() is what you need. Why do you want to hook a function into another function? Because there is functionality which is not accommodated by current function, so you want to extend it. I use add_action() ALOT in development of Genesis Child theme on WPNest. Since the Genesis Framework itself is loaded by many template hooks, all i need to do when i want to add new element on the child theme is hooking the template hook, instead of making a new template file. It makes me write less code and speeds up the development time once i get used to it.

Enough with the explanation, let’s have an example instead:

Let’s say you want to add this CSS on your <head>, because you want to hide your footer:

<style type="text/css">
    #footer {display:none;}
</style>

Instead of coding it directly into your header.php file, let’s do this the beautiful way: make it as a function, then hook it into wp_head() which should be available in <head> section of any good and standardized WordPress theme. These are what you should do, then:

1. Make it as a function

Open the theme’s functions.php file then type this function:

    function mytheme_css() {
    ?>
    <style type="text/css">
    #footer {display:none;}
    </style>
    <?php
    }

2. Hook the function you’ve just made into wp_head();

Type this function below the function you’ve just made:

    add_action("wp_head", "mytheme_css");

That’s it! If your theme has wp_head(); on its section, the wp_head() should output the CSS written in mytheme_css() function.

Well, I hope you find this short tutorial useful. 🙂

2 thoughts on “Hooking Function Using add_action()

  1. […] the script for further explanation. Basically what these functions do are printing a stylesheet and hooking it into wp_head() theme […]

  2. saya coba mengunakan share lagi dong artikel yang baru nya…?

Share Your Thought