10 Useful WordPress Hook Hacks


Hooks are very useful in WordPress. They allow you to “hook” a custom function to an existing function, which allows you to modify WordPress’ functionality without editing core files. In this article, we have compiled 10 extremely useful ready-to-use WordPress hooks, along with examples and coding explanations.

What Is A Hook?

To achieve a particular effect on a WordPress blog, you have to modify how WordPress works. Some of these modifications are made to what WordPress developers call “core files,” files required by WordPress to work properly.

But modifying core files is always a bad idea. It may create a security loophole. Also, you will have lost the modification when you upgrade your WordPress installation.

Still, developers need to overwrite some of WordPress’ functionality, which is why WordPress provides the Plugin API1.

Hooks are one of the main building blocks of WordPress plug-ins. Almost every plug-in uses a hook to overwrite WordPress’ core functionality.

How to Use Hooks on Your WordPress Blog

Unless you’re writing a plug-in, you would write hooks in the functions.php file. This file is located in the wp-content/themes/yourtheme directory.

A hook, as you would expect, “hooks” one function to another. For example, you could write a custom function and attach it to one of WordPress’ core functions:

add_action ( 'publish_post', 'myCustomFunction' );

In this example, we hook our own custom function to WordPress’ publish-post function, which means that every time WordPress executes the publish-post function, it will also execute this hooked function.

Of course, we can also remove hooks using the remove_action() function:

remove_action ( 'publish_post', 'myCustomFunction' );

Hooks resources:

1. Disable WordPress’ Automatic Formatting


The problem.
You have probably noticed that, by default, WordPress converts normal quotes to “curly” quotes, and makes other little formatting changes when a post is displayed.

This is very cool for people who publish normal content, but anyone who uses their blog to discuss code will be annoyed because, when pasted in a text editor, code with curly quotes returns syntax errors.

The solution.
Simply paste the following code in your functions.php file:

function my_formatter($content) {
  $new_content = '';
  $pattern_full = '{([raw].*?[/raw])}is';
  $pattern_contents = '{[raw](.*?)[/raw]}is';
  $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

  foreach ($pieces as $piece) {
    if (preg_match($pattern_contents, $piece, $matches)) {
      $new_content .= $matches[1];
    } else {
      $new_content .= wptexturize(wpautop($piece));

  return $new_content;

remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

add_filter('the_content', 'my_formatter', 99);

Once that’s done, you can use the [raw] shortcode in your posts:

[raw]This text will not be automatically formatted.[/raw]

Code explanation.
Our first step here was to create a function that uses a regular expression to find the [raw] shortcode in your posts’ content.

Then we hook our my_formatter() function to WordPress’ the_content() function, which means that my_formatter() will now be automatically called every time the_content() is called.

To remove the automatic formatting, we use the remove_filter() function, which lets you delete a hook on a specific function.


2. Detect The Visitor’s Browser Using A Hook


The problem.
Cross-browser compatibility is probably the most common problem in Web development. You will save yourself a lot of headaches if you are able to detect the browsers that people use to visit your website and then create a custom class wrapped in the body tag. Few people are aware of it, but WordPress can already detect browsers, and a few global variables are available for us to use.

The solution.
Nothing hard here: just paste the code below in your functions.php file, then save the file and you’re done!

function browser_body_class($classes) {
  global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

  if($is_lynx) $classes[] = 'lynx';
  elseif($is_gecko) $classes[] = 'gecko';
  elseif($is_opera) $classes[] = 'opera';
  elseif($is_NS4) $classes[] = 'ns4';
  elseif($is_safari) $classes[] = 'safari';
  elseif($is_chrome) $classes[] = 'chrome';
  elseif($is_IE) $classes[] = 'ie';
  else $classes[] = 'unknown';

  if($is_iphone) $classes[] = 'iphone';
  return $classes;

Once you have saved the file, the function will automatically add a CSS class to the body tag, as shown in the example below:

<body class="home blog logged-in safari">

Code explanation.
WordPress has global variables that return true if a visitor is using a particular browser. If the visitor’s browser is Google Chrome, the $is_chrome variable will return true. This is why we create the browser_body_class() function, which returns the name of the visitor’s browser. Once that’s done, we just hook the function to WordPress’ body_class() function.


3. Define Default Text In TinyMCE


The problem.
Many bloggers almost always use the same layout for their blog posts. Posts on my own blog WpRecipes.com are always displayed the same way: some text, some code and then some more text.

What about saving time by forcing tinyMCE (WordPress’ visual editor) to display default text?

The solution.
Once again, hooks are the solution. Just open your functions.php file, paste the code and let the hooks work their magic!

add_filter('default_content', 'my_editor_content');

function my_editor_content( $content ) {
  $content = "If you enjoyed this post, make sure to subscribe to my rss feed.";
  return $content;

Code explanation.
This code is powerful, and yet the method is so simple. Just create a function that returns the desired text (in this example, we have defined some simple text that asks readers to subscribe to the blog’s RSS feed), and hook the function to WordPress’ default_content() function. That’s it.


4. Insert Content Automatically After Each Post


The problem.
Most blogs use the single.php template to insert some text, images or ads just after a post. Sure, this can be done by opening single.php and pasting the desired text after the the_content() function. But the text won’t show up in your RSS feed? Hooks and the technique described below solve this problem.

The solution.
One again, simply paste the code below in the functions.php file of your theme. That’s it.

function insertFootNote($content) {
        if(!is_feed() && !is_home()) {
                $content.= "<div class='subscribe'>";
                $content.= "<h4>Enjoyed this article?</h4>";
                $content.= "<p>Subscribe to our  <a href='http://feeds2.feedburner.com/WpRecipes'>RSS feed</a> and never miss a recipe!</p>";
                $content.= "</div>";
        return $content;
add_filter ('the_content', 'insertFootNote');

Code explanation.
The purpose of the insertFootNote() function is pretty simple: it simply concatenates text of your choice to the $content variable, which contains your post’s content.

Then, our insertFootNote() function is hooked to the the_content() function, and it is automatically called every time the the_content is called. Using this function is basically the same as typing in the text at the end of each post.

Notice the (!is_feed) condition on line 2, which prevents the text from being inserted in the RSS feed. If you want the text to appear in your RSS feed, replace line 2 with the following:

if (!is_home()) {


5. Disable The “Please Update Now” Message On WordPress Dashboard


The problem.
Your dashboard automatically lets you know when a new version of WordPress is released by inserting a message at the top of admin pages. This is definitely a good thing, because updating gives your blog the latest functions and security fixes. But if the blog is a client project, letting the client control updates may not be a good idea.

The solution.
Just paste these four lines of code in your functions.php file:

if (!current_user_can('edit_users')) {
  add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
  add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );

Once you save functions.php, you won’t see the message on the dashboard.

Code explanation.
The first thing we do here is make sure the current user has sufficient administrative rights to update WordPress. Once we do that, we just create two hooks to overwrite the automatic check for updates and message display.


6. Disable WordPress From Auto-Saving Posts

Photo by thatcanadiangirl12

The problem.
As you type a post in the dashboard, WordPress periodically saves the content. This is a useful feature, but sometimes you may want to disable it.

The solution.
To disable WordPress’ auto-saving functionality, simply open the functions.php file and paste the following function:

function disableAutoSave(){
add_action( 'wp_print_scripts', 'disableAutoSave' );

Code explanation.
Again, nothing hard about this code. We simply create an action (on line 4) and hook the disableAutoSave() function that we created on line 1 to WordPress’ wp_print_scripts().

The result is that our disableAutoSave() function is called every time WordPress executes wp_print_scripts(). This way, we make sure the auto-save functionality is disabled.


7. Prevent Duplicate Content On Comment Pages


The problem.
Duplicate content is an SEO problem for many websites. It can also be a problem for your WordPress blog if you don’t apply a few tricks.

Introduced in version 2.7, paged comments is a great addition to WordPress because it lets bloggers split comments into multiple pages. The only problem, again, is the risk of duplicate content.

Let’s use the new rel="canonical" attribute to prevent duplicate content in paged comments.

The solution.
Simply paste the following code in your function.php file:

function canonical_for_comments() {
  global $cpage, $post;
  if ( $cpage > 1 ) :
    echo "n";
      echo "<link rel='canonical' href='";
      echo get_permalink( $post->ID );
      echo "' />n";

add_action( 'wp_head', 'canonical_for_comments' );

Code explanation.
First, we create a function to add the rel="canonical" attribute to comment pages, except page 1. Then we hook this function to WordPress’ wp_head() function. As simple as that!


8. Get Entire Post Or Page In A PHP Variable


The problem.
Being able to get the entire current post or page as a PHP variable is definitely a good thing. You could, for example, replace parts of the content using the str_replace() PHP function, and much more.

The solution.
Once again, nothing hard. Just paste the following in your function.php file.

function callback($buffer) {
  // modify buffer here, and then return the updated code
  return $buffer;

function buffer_start() {

function buffer_end() {

add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');

Code explanation.
To achieve this hack, we need three functions:

  • callback(): this function returns the whole page as a variable called $buffer. You can modify it before returning it by using regular expressions, for example.
  • buffer_start(): this function simply starts the buffer. It is hooked to WordPress’ wp_head() function.
  • buffer_end(): this function clears the buffer. It is hooked to WordPress’ wp_footer() function.

Once we have our function, we just hook it to existing WordPress functions.


9. Use Hooks And Cron To Schedule Events


The problem.
You probably already know that WordPress can schedule events. For example, it can publish posts at preset dates and times. Using hooks and wp-cron, we can easily schedule our own events. In this example, we will get our WordPress blog to send us an email once hourly.

The solution.
Paste the following code block in the functions.php file of your theme.

if (!wp_next_scheduled('my_task_hook')) {
  wp_schedule_event( time(), 'hourly', 'my_task_hook' );

add_action( 'my_task_hook', 'my_task_function' );

function my_task_function() {
  wp_mail('you@yoursite.com', 'Automatic email', 'Hello, this is an automatically scheduled email from WordPress.');

Code explanation.
The first thing we did, of course, was create a function that performs the desired action. In this example, the function is called my_task_function() and it just sends an email to the specified email address.

To schedule an event, we have to use the wp_schedule_event() function. The last argument has to be a hook, which is why we hook our my_task_function() function to my_task_hook.


10. List All Hooked Functions


The problem.
When things go wrong, listing all hooked functions can be very useful for debugging.

The solution.
As with the others, this code has to be pasted in your functions.php file. When you have finished debugging, don’t forget to remove the code from functions.php, or else the debugging message will continue to appear.

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

Once that’s done, simply call the list_hooked_functions() function, as shown below, to print all hooked WordPress functions on your screen.


Code explanation.
If no hook name is provided to the function as an argument, then hooks are printed to the screen using the global variable $wp_filter. Alternatively, you can list one particular hook by passing its name as an attribute:



You may be interested in the following related posts:



  1. 1 http://codex.wordpress.org/Plugin_API
  2. 2 http://codex.wordpress.org/Plugin_API
  3. 3 http://adambrown.info/p/wp_hooks
  4. 4 http://www.wprecipes.com/?s=hook
  5. 5 http://www.wprecipes.com/disable-wordpress-automatic-formatting-on-posts-using-a-shortcode
  6. 6 http://www.nathanrice.net/blog/browser-detection-and-the-body_class-function/
  7. 7 http://www.wprecipes.com/how-to-detect-the-visitor-browser-within-wordpress
  8. 8 http://justintadlock.com/archives/2009/04/05/how-to-preset-text-in-the-wordpress-post-editor
  9. 9 http://www.wprecipes.com/how-to-automatically-insert-text-in-wordpress-editor
  10. 10 http://www.wprecipes.com/how-to-automatically-insert-content-after-each-post
  11. 11 http://www.wprecipes.com/how-to-disable-the-please-update-now-message-in-wp-dashboard
  12. 12 http://www.flickr.com/photos/thatcanadiangirl/
  13. 13 http://www.wprecipes.com/wordpress-hook-disable-posts-auto-saving
  14. 14 http://www.wprecipes.com/wordpress-hack-canonical-links-for-comments
  15. 15 http://www.dagondesign.com/articles/wordpress-hook-for-entire-page-using-output-buffering/
  16. 16 http://blog.slaven.net.au/archives/2007/02/01/timing-is-everything-scheduling-in-wordpress/
  17. 17 http://www.rarst.net
  18. 18 http://www.smashingmagazine.com/2009/07/23/10-wordpress-comments-hacks/
  19. 19 http://www.smashingmagazine.com/2009/07/02/power-tips-for-wordpress-template-developers/
  20. 20 http://www.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks/
  21. 21 http://www.smashingmagazine.com/2009/05/13/10-custom-fields-hacks-for-wordpress/
  22. 22 http://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  23. 23 http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/

↑ Back to top Tweet itShare on Facebook

This guest post was written by Jean-Baptiste Jung, a 28-year-old blogger from Belgium, who blogs about Web Development on Cats Who Code, about WordPress at WpRecipes and about blogging on Cats Who Blog . You can stay in touch with Jean by following him on Twitter.

  1. 1

    Is it possible to do this?

    If i insert a tag like [pretext] in my post while writing, it has to replace it with something like this “This is the preset text” in the post that has been published…

    • 52

      Yeah, go to edit your functions.php file and add this line:

      function preset() {
      return ‘This is the preset text';

      This code adds a function called “pretext” that returns a line when its used. There can be html and php values too.

      And then, below that line add this:

      add_shortcode(‘pretext’, ‘preset’);

      This will add shortcode, the first property (pretext) is the value that will be in “[ ]” to return the value given in the first code line. And the second property (preset) calls a function named “preset”, the function exists and if you write [pretext] in your post, this shortcode will search a function called “preset”, if it exist (exists) the value given will be displayed.

      Now when published, will be displayed:
      This is the preset text

      You can use ADsense too ;)

  2. 103

    Quite possibly the most useful list I’ve ever read, thanks for posting this.

  3. 154
  4. 205

    Very good information. Duplicate content is a problem we must avoid, you can see the solution that I created to minimize its effects.


    I hope this helps.

  5. 256

    Old post, but still useful :)

    Thanks so much to the Cats ;) #kidding

  6. 307

    Number 2 is very useful. But how to observe the amount of users who use each browser once I place the code in the php file? In other words, once I write the hook, how do I monitor the browsers that my users are using?

  7. 358

    Thanks so much. Really helpful post.


↑ Back to top