WordPress Essentials: The Definitive Guide To WordPress Hooks

Advertisement

If you’re into WordPress development, you can’t ignore hooks for long before you have to delve into them head on. Modifying WordPress core files is a big no-no, so whenever you want to change existing functionality or create new functionality, you will have to turn to hooks.

wp-hooks-guide1

In this article, I would like to dispel some of the confusion around hooks, because not only are they the way to code in WordPress, but they also teach us a great design pattern for development in general. Explaining this in depth will take a bit of time, but bear with me: by the end, you’ll be able to jumble hooks around like a pro.

Why Hooks Exist

I think the most important step in grasping hooks is to understand the need for them. Let’s create a version of a WordPress function that already exists, and then evolve it a bit using the “hooks mindset.”

function get_excerpt($text, $length = 150) {
      $excerpt = substr($text,$length)
      return $excerpt;
   }

This function takes two parameters: a string and the length at which we want to cut it. What happens if the user wants a 200-character excerpt instead of a 150-character one? They just modify the parameter when they use the function. No problem there.

If you use this function a lot, you will notice that the parameter for the text is usually the post’s content, and that you usually use 200 characters instead of the default 150. Wouldn’t it be nice if you could set up new defaults, so that you didn’t have to add the same parameters over and over again? Also, what happens if you want to add some more custom text to the end of the excerpt?

These are the kinds of problems that hooks solve. Let’s take a quick look at how.

function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length", $length);

      $excerpt = substr($text,$length)
      return $excerpt;
   }

As you can see, the default excerpt length is still 150, but we’ve also applied some filters to it. A filter allows you to write a function that modifies the value of something — in this case, the excerpt’s length. The name (or tag) of this filter is excerpt_length, and if no functions are attached to it, then its value will remain 150. Let’s see how we can now use this to modify the default value.

function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length");

      $excerpt = substr($text,$length)
      return $excerpt;
   }

   function modify_excerpt_length() {
      return 200;
   }

   add_filter("excerpt_length", "modify_excerpt_length");

First, we have defined a function that does nothing but return a number. At this point, nothing is using the function, so let’s tell WordPress that we want to hook this into the excerpt_length filter.

We’ve successfully changed the default excerpt length in WordPress, without touching the original function and without even having to write a custom excerpt function. This will be extremely useful, because if you always want excerpts that are 200 characters long, just add this as a filter and then you won’t have to specify it every time.

Suppose you want to tack on some more text, like “Read on,” to the end of the excerpt. We could modify our original function to work with a hook and then tie a function to that hook, like so:

function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length");

      $excerpt = substr($text,$length)
      return apply_filters("excerpt_content", $excerpt);
   }

   function modify_excerpt_content($excerpt) {
      return $excerpt . "Read on…";
   }
   add_filter("excerpt_content", "modify_excerpt_content");

This hook is placed at the end of the function and allows us to modify its end result. This time, we’ve also passed the output that the function would normally produce as a parameter to our hook. The function that we tie to this hook will receive this parameter.

All we are doing in our function is taking the original contents of $excerpt and appending our “Read on” text to the end. But if we choose, we could also return the text “Click the title to read this article,” which would replace the whole excerpt.

While our example is a bit redundant, since WordPress already has a better function, hopefully you’ve gotten to grips with the thinking behind hooks. Let’s look more in depth at what goes on with filters, actions, priorities, arguments and the other yummy options available.

Filters And Actions

Filters and actions are two types of hooks. As you saw in the previous section, a filter modifies the value of something. An action, rather than modifying something, calls another function to run beside it.

A commonly used action hook is wp_head. Let’s see how this works. You may have noticed a function at the bottom of your website’s head section named wp_head(). Diving into the code of this function, you can see that it contains a call to do_action(). This is similar to apply_filters(); it means to run all of the functions that are tied to the wp_head tag.

Let’s put a copyright meta tag on top of each post’s page to test how this works.

add_action("wp_head", "my_copyright_meta");

   function my_copyright_meta() {
      if(is_singular()){
         echo "";
      }
   }

The Workflow Of Using Hooks

While hooks are better documented nowadays, they have been neglected a bit until recently, understandably so. You can find some good pointers in the Codex, but the best thing to use is Adam Brown’s hook reference2, and/or look at the source code3.

Say you want to add functionality to your blog that notifies authors when their work is published. To do this, you would need to do something when a post is published. So, let’s try to find a hook related to publishing.

Can we tell whether we need an action or a filter? Sure we can! When a post is published, do we want to modify its data or do a completely separate action? The answer is the latter, so we’ll need an action. Let’s go to the action reference4 on Adam Brown’s website, and search for “Publish.”

The first thing you’ll find is app_publish_post. Sounds good; let’s click on it. The details page doesn’t give us a lot of info (sometimes it does), so click on the “View hook in source” link next to your version of WordPress (preferably the most recent version) in the table. This website shows only a snippet of the file, and unfortunately the beginning of the documentation is cut off, so it’s difficult to tell if this is what we need. Click on “View complete file in SVN” to go to the complete file so that we can search for our hook.

In the file I am viewing, the hook can be found in the _publish_post_hook() function, which — according to the documentation above it — is a “hook to schedule pings and enclosures when a post is published,” so this is not really what we need.

With some more research in the action list, you’ll find the publish_post hook, and this is what we need. The first thing to do is write the function that sends your email. This function will receive the post’s ID as an argument, so you can use that to pull some information into the email. The second task is to hook this function into the action. Look at the finished code below for the details.

function authorNotification($post_id) {
      global $wpdb;
      $post = get_post($post_id);
      $author = get_userdata($post->post_author);

      $message = "
         Hi ".$author->display_name.",
         Your post, ".$post->post_title." has just been published. Well done! 
      ";
      wp_mail($author->user_email, "Your article is online", $message);
   }
   add_action('publish_post', 'authorNotification');

Notice that the function we wrote is usable in its own right. It has a very specific function, but it isn’t only usable together with hooks; you could use it in your code any time. In case you’re wondering, wp_mail() is an awesome mailer function — have a look at the WordPress Codex5 for more information.

This process might seem a bit complicated at first, and, to be totally honest, it does require browsing a bit of documentation and source code at first, but as you become more comfortable with this system, your time spent researching what to use and when to use it will be reduced to nearly nothing.

Priorities

The third parameter when adding your actions and filters is the priority. This basically designates the order in which attached hooks should run. We haven’t covered this so far, but attaching multiple functions to a hook is, of course, possible. If you want an email to be sent to an author when their post is published and to also automatically tweet the post, these would be written in two separate functions, each tied to the same tag (publish_post).

Priorities designate which hooked function should run first. The default value is 10, but this can be changed as needed. Priorities usually don’t make a huge difference, though. Whether the email is sent to the author before the article is tweeted or vice versa won’t make a huge difference.

In rarer cases, assigning a priority could be important. You might want to overwrite the actions of other plugins (be careful, in this case), or you might want to enforce a specific order. I recently had to overwrite functionality when I was asked to optimize a website. The website had three to four plugins, with about nine JavaScript files in total. Instead of disabling these plugins, I made my own plugin that overwrote some of the JavaScript-outputting functionality of those plugins. My plugin then added the minified JavaScript code in one file. This way, if my plugin was deactivated, all of the other plugins would work as expected.

Specifying Arguments

The fourth argument when adding filters and actions specifies how many arguments the hooked function takes. This is usually dictated by the hook itself, and you will need to look at the source to find this information.

As you know from before, your functions are run when they are called by apply_filters() or do_action(). These functions will have the tag as their first argument (i.e. the name of the hook you are plugging into) and then passed arguments as subsequent arguments.

For example, the filter default_excerpt receives two parameters, as seen in includes/post.php.

$post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );

The arguments are well named — $post_excerpt and $post — so it’s easy to guess that the first is the excerpt text and the second is the post’s object. If you are unsure, it is usually easiest either to look further up in the source or to output them using a test function (make sure you aren’t in a production environment).

function my_filter_test($post_excerpt, $post) {
      echo "<pre>";
         print_r($post_excerpt);
         print_r($post);
      echo "</pre>";
   }
   add_filter("default_excerpt", "my_filter_test");

Variable Hook Names

Remember when we looked at the publish_post action? In fact, this is not used anymore; it was renamed in version 2.3 to {$new_status}_{$post->post_type}. With the advent of custom post types, it was important to make the system flexible enough for them. This new hook now takes an arbitrary status and post type (they must exist for it to work, obviously).

As a result, publish_post is the correct tag to use, but in reality, you will be using {$new_status}_{$post->post_type}. A few of these are around; the naming usually suggests what you will need to name the action.

Who Is Hooked On Who?

To find out which function hooks into what, you can use the neat script below, courtesy of WP Recipes6. Use this function without arguments to get a massive list of everything, or add a tag to get functions that are hooked to that one tag. This is a great one to keep in your debugging tool belt!

function list_hooked_functions($tag=false){
 global $wp_filter;
 if ($tag) {
  $hook[$tag]=$wp_filter[$tag];
  if (!is_array($hook[$tag])) {
  trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
  return;
  }
 }
 else {
  $hook=$wp_filter;
  ksort($hook);
 }
 echo '<pre>';
 foreach($hook as $tag => $priority){
  echo "<br /><strong>$tag</strong><br />";
  ksort($priority);
  foreach($priority as $priority => $function){
  echo $priority;
  foreach($function as $name => $properties) echo "t$name<br />";
  }
 }
 echo '</pre>';
 return;
}

Creating Your Own Hooks

A ton of hooks are built into WordPress, but nothing is stopping you from creating your own using the functions we’ve looked at so far. This may be beneficial if you are building a complex plugin intended for wide release; it will make your and other developers’ jobs a lot easier!

In the example below, I have assumed we are building functionality for users to post short blurbs on your website’s wall. We’ll write a function to check for profanity and hook it to the function that adds the blurbs to the wall.

Look at the full code below. The explanation ensues.

function post_blurb($user_id, $text) {

      $text = apply_filters("blurb_text", $text);

      if(!empty($text)) {
         $wpdb->insert('my_wall', array("user_id" => $user_id, "date" => date("Y-m-d H:i:s"), "text" => $text), array("%d", %s", "%s"));   
      }
   }

   function profanity_filter($text) {
      $text_elements = explode(" ", $text);
      $profanity = array("badword", "naughtyword", "inappropriatelanguage");

      if(array_intersect($profanity, $text_elements)) {
         return false;
      }
      else {
         return $text;
      }      
   }

   add_filter("blurb_text", "profanity_filter");

The first thing in the code is the designation of the function that adds the blurb. Notice that I included the apply_filters() function, which we will use to add our profanity check.

Next up is our profanity-checking function. This checks the text as its argument against an array of known naughty words. By using array_intersect(), we look for array elements that are in both arrays — these would be the profane words. If there are any, then return false; otherwise, return the original text.

The last part actually hooks this function into our blurb-adding script.

Now other developers can hook their own functions into our script. They could build a spam filter or a better profanity filter. All they would need to do is hook it in.

Mixing And Matching

The beauty of this system is that it uses functions for everything. If you want, you can use the same profanity filter for other purposes, even outside of WordPress, because it is just a simple function. Already have a profanity-filter function? Copy and paste it in; all you’ll need to do is add the one line that actually hooks it in. This makes functions easily reusable in various situations, giving you more flexibility and saving you some time as well.

That’s All

Hopefully, you now fully understand how the hooks system works in WordPress. It contains an important pattern that many of us could use even outside of WordPress.

This is one aspect of WordPress that does take some time getting used to if you’re coming to it without any previous knowledge. The biggest problem is usually that people get lost in all of the filters available or in finding their arguments and so on, but with some patience this can be overcome easily. Just start using them, and you’ll be a master in no time!

(al)

Footnotes

  1. 1 http://www.smashingmagazine.com/2011/10/07/definitive-guide-wordpress-hooks/
  2. 2 http://adambrown.info/p/wp_hooks
  3. 3 http://core.trac.wordpress.org/browser/tags/
  4. 4 http://adambrown.info/p/wp_hooks/hook/actions
  5. 5 http://codex.wordpress.org/Function_Reference/wp_mail
  6. 6 http://www.wprecipes.com/list-all-hooked-wordpress-functions

↑ Back to topShare on Twitter

Hallo, my name is Daniel :) I build plugins, themes and apps - then proceed to write or talk about them. I'm the editor for the WordPress section here on Smashing Magazine and I contribute to various other online sites. When not coding or writing you'll find me playing board games or running with my dog. Drop me a line on Twitter or visit my personal website.

Advertising

Note: Our rating-system has caused errors, so it's disabled at the moment. It will be back the moment the problem has been resolved. We're very sorry. Happy Holidays!

  1. 1

    Great article, definitely on my to-read list

  2. 2

    Snippet for dumping hooks from WPRecipes (courtesy of me :) it very outdated, it won’t handle hooked methods properly and such. A set of newer and more robust code written up here: http://www.rarst.net/script/debug-wordpress-hooks/

  3. 4

    Hooray! I missed this article so much! Thanks, guys.

  4. 5

    Great article thanks !
    Are some of the earlier examples that have this line:

    $excerpt = substr($text,$length)

    Missing the closing ; ?

    Regards, Dave

  5. 6

    Great Article.
    Very basic and interesting…
    Thanks Daniel
    :)

  6. 7

    Great article. Just starting out with wordpress and been dabbling with hooks – I think they are beautiful! Blown away by how easy it becomes to alter functionality without messing with any core code. Love ‘em.

    Thanks for clarifying the process, taken alot from your article.

    Cheers, Ste.

  7. 9

    It’s good to read a great article like this, keep going Daniel!
    Thanks!

    Mostanában egyre többet írsz a SM-nek, csak így tovább Dániel!
    Köszi!

  8. 10

    Very nice post thanks for share Daniel Pataki

  9. 11

    OMG stooooop with all the WordPress articles, geez.

    • 12

      No!!! Please keep up with it, this is great stuff and there’s no one better to do it than Smashing Magazine! Cheers to the good work.

  10. 13

    This comment is *not* directed at the author.

    I’m not trying to complain, but as a senior level PHP developer, I’m finding myself befuddled at the number of WordPress articles that popular sites and blogs keep publishing. These sites and blogs all claim to cater to web developers and web designers, yet seem to have some sort of tunnel vision as to who those people actually are.

    WordPress is an amazing tool, and certainly has a vital role in web development and design for many individuals, businesses, and organizations. I do *not* believe WordPress is just a hobbyist’s tool, as many in my type of career field are arrogant enough to insist on. I believe WordPress has much to offer for many small businesses, online stores, or even large corporations who need to improve their online presence. However, for those of us who are developing custom enterprise level applications with databases containing tens of millions of records, WordPress simply has no part in our daily tasks.

    I’m not bashing WordPress, but I’m finding “high-level” articles on various aspects of web development to be more and more elusive these days. I occasionally see a halfway decent Zend or Code Igniter article getting posted, which is always refreshing, but I would love to see some fresh articles that focused on things like version control, naming conventions, database abstraction, code architecture, documentation standards, etc. – things that don’t even necessarily have to be tied to a specific programming language.

    As the senior programmer in our company, I can’t tell anybody how frustrating it is to actually find people who know what they’re doing. We get hundreds of applications for every job opening we post from people who think that knowing WordPress, Joomla, Drupal, and the little PHP they wrote and utilized in those applications somehow makes them a qualified programmer. They also love mentioning that four-year degree in computer science they attained a few years ago. With each passing day, it seems harder to find the right people for even an entry level position, and I think a majority of the reason for this is because people like me, who are completely self-taught, are harder to come by. And *one of the reasons* self-taught individuals are harder to come by is because too many “web developer” and “web designer” sites are catering to (pardon the slang term) n00bs.

    Folks, if WordPress is all you know or are willing to learn, you’re limiting your own potential, because people like me will tell HR to not even consider you for the position.

    • 14

      I feel your pain Henri; it does get a little tiring hearing about the web’s golden boys (WP and jQuery), but I worry about your last statement. When everybody is eating hamburgers, how can you fault a cook for putting them on the menu? Does being able to cook one necessarily mean they couldn’t serve Beef Wellington?

      I have experience with what tools I use. I use what tools my clients/bosses want. When doing free-lance work on small scale sites there is absolutely nothing that sells as well as WP. This doesn’t mean that I don’t have aspirations of more substantial projects, just that I enjoy paying my rent and occasionally eating food.

      Although a CV can contain all kinds of red-flags and warning bells for a veteran eye, I cringe when I hear of such sweeping generalizations being passed down to the monkeys who handle application validation in HR departments. These are generally the lowest-level workers, operating within very narrow boundaries, with little to no flexibility as to how they apply the rules which they have been given to screen applicants.

      Experience with common CMSs can certainly be a reason to follow up with targeted interview questions, but I hope that you haven’t been missing out on the “right people” that you’ve been looking for, just because those same intelligent, adaptable programmers have been wiser than to push against the tide.

      • 15

        Hi Kevin,

        I actually completely agree with about 95% of what you say. If I were hiring someone and he/she wrote “WordPress” as a skill, I would throw away the resume. Writing “I know WordPress” is like writing “I know how cars work” because I can drive one.

        The point Kevin is making is that the skills involved in being a good WordPress developer is PHP and MySQL, and the usual suspects, not WordPress itself. On a very real level, WordPress is nothing more than a bundle of functions.

        I also think it is unfair to say “You should be writing articles”. I can play the guitar pretty well, just because I don’t write articles on it, I can still criticize other players.

        So here comes the point on which I disagree. I think WordPress is a stepping stone to learning higher level PHP and other languages. A WP section can never be for the top of the line experts since they don’t need WP articles. I don’t know everything about WP, but for me browsing through the source code is faster than reading an article since I understand the underlying mechanics.

        I disagree for the exact same reasons you bring up. If you are professional developer you don’t need WordPress articles, since nothing WordPress does should be new to you.

        Its very rare to receive such constructive criticism, I wish others would follow in your wake. I am sure there will be much higher level articles coming, but I think getting the basics out of the way is a good way to launch a new section :)

    • 16

      Sounds like you and your keyboard need to get to work and do some article writing. You seem to want to read articles that, if your self proclamation is true, you could be writing your self. There comes a time, when you attain a certain level of proficiency, that you must give back to your community, instead of consuming and complaining. Put your money where your mouth is so to speak. Get to it. We noobs (you know the ones you have such distain for) are looking forward to hearing from you.

      • 17

        G Thompson,

        You seem to be misunderstand my point. With all due respect, your attitude seems equivalent to you saying a professional vocalist has no business buying other people’s music or going to a music concert. It’s like you’re saying that Enya from Ireland is abusing the music industry, as well as her fans, because she’s never held a live concert…

        I give back plenty in other areas of my life, and am not obligated to write articles for you or anyone else. However, SM is a resource that is claimed to be targeted at people like me (and you too). SM is also a commercial service, because it generates advertising revenue, and the people behind it get paid (financially or otherwise). Basically, SM is a business, and as a consumer, I have the right to criticize or complain about a product or service that is not meeting my expectations. If SM was non-profit, I’d be less inclined to criticize or complain… Economics 101, my friend.

        The point I was trying to make is that many of today’s resources that claim to be targeted at web developers and web designers (such as SM), appear to have a tunnel vision for who those people are. They often appear to leave those of us with, by general definition, “more experience,” out of the picture almost entirely.

        I have absolutely no disdain for n00bs. In fact, that’s exactly the point I’m trying to make. You’re never going to leave behind the status of “n00b” if the resources available, which claim to be “professional resources,” don’t present you with anything more advanced than WordPress articles.

        • 18

          I only suggest humbly, that you might learn much more from teaching a topic, than you ever could by simply reading an article or two. Also I feel that SM is more than just a business and we are all more than consumers here. We are a community and we all benefit from each other, and the input and instruction shared. You certainly are free to be, only a consumer. I would venture to say, however, that you could get so much more out of the community with a slight shift in perspective. After all the community GIVE and take is why SM is so popular and heavily trafficked. UX design 101… my friend.

        • 19

          The only thing I don’t get is why post a comment when you clearly know you’re barking up the wrong tree and you’re not the target audience. Just needed to get it off your chest and this was the final drop that tipped the bucket?
          I’m not saying I disagree btw, but according to your own Economics 101 you’re a dying breed and therefor not interesting to target with articles at your level.

    • 20

      word. Heri, I want to learn from you!

    • 21

      Agreed. I know a couple of people who create a couple of sites in WordPress and claim to be able to do PHP. Download WP > Apply Template > Tinker for a couple of nights and they know it all :P

      I would also like to see some more of the other articles but I think these people have better things to do and are a lot busier.

    • 22

      @Heri – Why not come hang out at http://wordpress.stackexchange.com. I think you’ll find a higher calibre over there.

  11. 23

    The 3rd and 4th code blocks are missing the $length parameter in the apply_filters() function. Without it, it’s only ever capable of returning false or the return value from the hook – never actually sending information to be manipulated by the filter.

  12. 25

    Excellent article, thank you. I figured out most of it when I built my first theme, but it’s nice to see it clearly laid out to fill in any gaps.

    I must admit, though, that I found the ‘Variable Hook Names’ utterly confusing, and I had no idea what you were actually saying we should use in that particular case. (I guess I’ll figure it out by looking at the WP code if I ever need to use it, though.)

  13. 26

    That’s exactly what i was looking for… nice post!

  14. 27

    Very helpful stuff! Thanks so much, really appreciate it.

  15. 28

    very helpful..

  16. 29

    Syntax error on line 5 of “Filters And Actions”

  17. 30

    Very good tutorial, however I couldn’t get the excerpt_content to work so it displays ‘Read more…’ i tried replacing the excerpt_content with the excerpt_more and it displays the text but it’s not linked to the post, how do I get your code to work?

  18. 31

    This code does not work and it’s discouraging to follow along when the code isn’t properly checked to make sure it works as it was intended:

    function get_excerpt($text, $length = 150) {

    $length = apply_filters(“excerpt_length”);

    $excerpt = substr($text,$length)
    return apply_filters(“excerpt_content”, $excerpt);
    }

    function modify_excerpt_content($excerpt) {
    return $excerpt . “Read on…”;
    }
    add_filter(“excerpt_content”, “modify_excerpt_content”);

  19. 32

    Frankly, this comment, while it brings up great points, is sorely misplaced in my opinion.

    I think there should be an article dealing with the disambiguation of ‘web designer’, ‘web developer’, and ‘programmer’. There is obviously cross over between all three, but there are also definite distinctions as well.

    This article is clearly written for designers, and a certain level of developers, but not programmers unless they have a need to program a WordPress based web-app and have never used it before. In any case, it’s an article about WordPess hooks, and that’s what it talks about. If you are interested in code architecture theory, why read an article about WP hooks? To me that’s like reading an article about how to throw together a basic Marinara Sauce and then complaining that you didn’t learn enough about the heat resistance of egg whites in preparing Hollondaise Sauce. Yeah they are both sauces, and yes you are cooking and even using the same equipment, but it’s a guide to marinara….

    To be clear, I would love to see articles on higher level development and programming structures, best practices, and theory, but don’t take away from the specific recipes. WordPress dwarfs any other CMS in sheer number, especially in the realm of web designers, so why not write about that?

  20. 33

    Excellent article on hooks. I get asked all the time what hooks are for WP. It is so much ‘safer’ than editing core files. – John

  21. 34

    Just thought I’d throw in my two cents. Personally I found this article really helpfull. I think the point made by Daniel Pataki is a very valid one that WP is an excellent gateway to learning PHP and SQL and this is certainly true in my case. Like most SM readers I like learning thru helpful articles and trial and error. It seems odd that someone would “complain” about the contents of an article which clearly was not intended for them. I wouldn’t dream of reading a CSS 101, but would not feel the need to comment on its existence.

    Anyway, thanks for a really helpful article, it cleared up a lot of basic concepts I was struggle with (avoiding).

  22. 35

    Thank you understood very readable and although I was poor at English.

  23. 36

    Great article Daniel,

    I always struggle to find what hooks are available and understanding how they work is another uphill battle.
    You’ve provided me with a workflow that is going to make wordpress development a lot easier.

    Cheers,
    Edwin

  24. 37

    Hi,
    I am trying to hook into the ‘bloginfo_url’ filter of the get_bloginfo() function in the wp-includes/general-template.php file. What I am trying to do is modify the url in the admin Visit Site from home_url() to another page. The code that Iwant to change is in the wp-admin/admin-header.php;

    <a href="” title=””>

    I have added the following into the functions.php file in the them directory:

    add_filter(‘bloginfo_url’, ‘mybloginfo’, 1, 2);
    apply_filters(‘bloginfo_url’, $output, $show);

    function mybloginfo($result=”, $show=”) {

    $cur_user =wp_get_current_user();
    $primary_url = get_blogaddress_by_id($cur_user->primary_blog);
    $usr_roles = $cur_user->roles;
    $usr_role = array_shift($usr_roles);

    if($usr_role==’custom1′)
    $h_url = $primary_url . “home1.php”;
    else if($usr_role==’custom2′)
    $h_url = $primary_url . “home2.php”;
    else if($usr_role==’custom3′)
    $h_url = $primary_url . “home3.php”;
    else
    $h_url = $primary_url . “home1.php”;

    switch ($show) {
    case ‘url':
    $result = untrailingslashit($h_url);
    break;
    default:
    }
    return $result;
    }

    I have sprinkled some print code to see if the values are being changed and they are, but the home_url() ends up being the url instead of the url in my callback function.

    What is going on?

    Any help would be appreciated!

    Regards,
    Raynbow

  25. 38

    This is was fairly poorly edited article.

    Examples:

    Line 5 from Filters and Actions section.

    And from the first four code examples of the article, missing the semi-colons:

    $excerpt = substr($text,$length)

  26. 39

    Great introductory article, but, as with many WP “articles” this is another rehash of the codex files, minus any juice. You briefly mention priorities on hooks, where are the examples? You briefly mention passing arguments to hooks, where are the do_action equivalents and some examples?

    And what if your hook requires args but the designer using your do_action hook doesn’t pass any? (an undefined offset error is thrown – most wp “developers” don’t know this of course because they have wp_debug set to false – bad practice).

    I agree with some of the comments above, the n00b articles are handy, but how about finishing the job with some serious examples covering all the aspects of hooks? Otherwise call the article “Introduction to…” not “Definitive guide”, because it isn’t definitive by any means.

  27. 40

    Thanks a lot. Really good synthesis.
    If I may, I prefer automatic updates regarding date so I’d add an echo date (‘Y’).

  28. 41

    Thanks for the synthesis. However that would be better to use date(‘Y’) for the meta copyright.

  29. 42

    Dear,

    I have one question.
    In the example above in this tutorial, it’s about the excerpt.

    [code]
    function get_excerpt($text, $length = 150) {

    $length = apply_filters(“excerpt_length”);

    $excerpt = substr($text,$length)
    return $excerpt;
    }

    function modify_excerpt_length() {
    return 200;
    }

    add_filter(“excerpt_length”, “modify_excerpt_length”);
    [/code]

    How works and looks like the output of the excerpt. You was saying, “and if no functions are attached to it, then its value will return 150.”

    Do you meaning, when uses the following snippet of code: The output will be return 200 words of the main content, because i’m now attaching the function for 200 words to the excerpt. And when you call the normal one like this: It will return the default length of 150 words, because I have set no parameters to the hook the_excerpt. ?

    And when I copy/paste the code in this reaction into my functions.php file, I get white screen in WordPress. What does I wrong?
    Thank you very much.
    Kind regards,

    Casper B

  30. 43

    very good post but I have one question:
    I am writing a plugin that uses init() hook to check cookies and then the_content() hook to modify content based on the cookies. What is the best method to pass a variable $cookie_is_set between these two hooks? I need a proper solution, not dirty hack ;)
    Best regards!

  31. 44

    I don’t claim to be an expert in MySql or PHP, however i do know more than the average i guess.

    When i see a post like this on SM; i think this is great content for a new comers trying to learn a new skill or technique .

    Personally i prefer coming over to SM for these tutorials than reading the overly explained or sometimes vague WordPress codex that can be daunting to new users.

    I build themes and plug-ins for WordPress, as well as build sites for clients.
    I’m not a programmer, I’m a web designer and this kind of article was made for me.

    Great article…

    Cheers
    Daniel

  32. 45

    Hello,

    Thanks for the great article. But wp_head action hook is not working, kindly assist.

    Thanks

  33. 46

    Great article!.
    This is very useful to anybody who wants starting developing in wordpress.

  34. 47

    this explanation is a hundred times better than the ones i read in the WordPress books I bought. It’s not that complicated, yet nobody seems to been able to do it until you, at least that I’ve seen. thanks!

  35. 48

    T H A N K S : )

  36. 49

    This was immensely helpful! Great examples. Helped illustrate ellusive concepts for the less than hard core developers out there!! Thanks Daniel!!

  37. 50

    Daniel Meschiany

    April 3, 2014 5:42 am

    Hey Daniel,
    Great article, it arranged a few things in my head.

    One question please, If i add for example:
    add_action(‘admin_head’,’zkr_profile_upload_js’);
    in users.php file, how does wp know that it has a function connected to the hook admin_head?

    thanks, Cheers

  38. 51

    Panji Tri Atmojo

    June 2, 2014 5:49 am

    The easiest-to-understand tutorial on WP Hooks yet =), good job

↑ Back to top