10 Useful Wordpress Hooks

Original author: Jean-Baptiste Jung
  • Transfer
image
About what are hooks in Wordpress and how to use them there. An article by a young Wordpress specialist, owner of www.wprecipes.com , from Belgium.

INTRODUCTION


Hooks are very useful features in Wordpress. They make it possible to “hook” a user-defined function “on the hook” of an existing function, thereby allowing you to change Wordpress functionality without making changes to the engine core files. In this article, we present to you 10 particularly useful, ready-to-use hooks for Wordpress, with examples and explanations of their source code.

WHAT IS A HOOK?


To achieve a certain effect, we need to slightly change how Wordpress works. Some modifications need to be made to the files that the developers called kernel files — they are necessary for Wordpress to work properly.
But modifying kernel files is a bad idea: this can create a security hole in your blog. Also, all modifications will disappear as soon as you upgrade the engine to a new version.
However, enhanced functionality is still necessary. To do this, the developers invented the Plugin API.
Hooks are one of the main blocks for building plugins. Almost every plug-in uses hooks to extend Wordpress functionality.

HOW TO USE HOOKIES IN YOUR BLOG


Until you have written your plugin, you must write the hooks to the functions.php file . This file is located in the wp-content / themes / yourtheme directory (where / yourtheme is the directory where the current theme is located).
Here is an example that shows how to connect your custom function to the engine core function:

  1. add_action ('publish_post', 'myCustomFunction');


In this example, we connected the user-defined function myCustomFunction () to the kernel function publish_post () . The myCustomFunction () function will be executed each time the publish_post () function is executed .
Of course, we can also remove the hook using the remove_action () function :

  1. remove_action ('publish_post', 'myCustomFunction');


1. DISABLED AUTOMATIC FORMATTING IN WORDPRESS


Problem.

You have probably already noticed that the Wordpress typographer by default turns “direct” quotes into “curves” and makes other minor changes to the formatting of the post.
This is good if the blogger posts regular content (plain text and images are implied). But some will post the source code to discuss later, and they will be very unhappy when, due to these “crooked” quotes, the interpreter or compiler will give them messages about syntax errors.

Decision.

Just paste the following code into the functions.php file :

  1. function my_formatter ($ content) {
  2. $ new_content = '';
  3. $ pattern_full = '{(\ [raw \]. *? \ [/ raw \])} is';
  4. $ pattern_contents = '{\ [raw \] (. *?) \ [/ raw \]} is';
  5. $ pieces = preg_split ($ pattern_full, $ content, -1, PREG_SPLIT_DELIM_CAPTURE);
  6.  
  7. foreach ($ pieces as $ piece) {
  8. if (preg_match ($ pattern_contents, $ piece, $ matches)) {
  9. $ new_content. = $ matches [1];
  10. } else {
  11. $ new_content. = wptexturize (wpautop ($ piece));
  12. }
  13. }
  14.  
  15. return $ new_content;
  16. }
  17.  
  18. remove_filter ('the_content', 'wpautop');
  19. remove_filter ('the_content', 'wptexturize');
  20.  
  21. add_filter ('the_content', 'my_formatter', 99);


After you have done this, you can use the [raw] tag so that the post text is not formatted automatically:

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



Code explanation.

First of all, we create a function that, based on regular expressions, finds the [raw] tag in the content of your post.
Next, we bind our my_formatter () function to the the_content () function , which means that our function will execute whenever the thecontent () function is called .
In order to disable autoformatting, we used the remove_filter () function .

2. DETERMINE THE VISITOR BROWSER BY HOOK


Problem.

Cross browser compatibility is the most common problem in web development. You will save a lot of nerves and time if you can determine the browser of the user who has visited your blog, and then create a CSS class for the body tag for each of the browsers.

Decision.

Nothing complicated: just paste the following code into the functions.php file , save it - you're done!

  1. add_filter ('body_class', 'browser_body_class');
  2. function browser_body_class ($ classes) {
  3. global $ is_lynx, $ is_gecko, $ is_IE, $ is_opera, $ is_NS4, $ is_safari, $ is_chrome, $ is_iphone;
  4.  
  5. if ($ is_lynx) $ classes [] = 'lynx';
  6. elseif ($ is_gecko) $ classes [] = 'gecko';
  7. elseif ($ is_opera) $ classes [] = 'opera';
  8. elseif ($ is_NS4) $ classes [] = 'ns4';
  9. elseif ($ is_safari) $ classes [] = 'safari';
  10. elseif ($ is_chrome) $ classes [] = 'chrome';
  11. elseif ($ is_IE) $ classes [] = 'ie';
  12. else $ classes [] = 'unknown';
  13.  
  14. if ($ is_iphone) $ classes [] = 'iphone';
  15. return $ classes;
  16. }


After you save the file, the function will automatically add a CSS class corresponding to the user’s browser for the body tag :



Code explanation.

Wordpress has global variables that return true if the user uses the appropriate browser. If the user uses the Google Chrome browser, the $ is_chrome variable will be true . That's why we create the browser_body_class () function . After that, we attach it to the wordpress function body_class () .

3. DEFINITION OF TEXT FOR DEFAULT IN TinyMCE EDITOR


Problem.

Many bloggers almost always use the same format for their blog. The posts on my WpRecipes.com blog are always displayed the same: text, code, some more text.
You can save a lot of time if you teach TinyMCE to display some text by default.

Decision.

As always, the solution is a hook. Copy the code to the functions.php file and see how it works.

  1. add_filter ('default_content', 'my_editor_content');
  2.  
  3. function my_editor_content ($ content) {
  4. $ content = "If you enjoyed this post, make sure to subscribe to my rss feed.";
  5. return $ content;
  6. }


Code explanation.

This code, although simple, is very powerful. We simply create a function that returns the required text (in this example, we define the text that asks visitors about subscribing to the RSS feed) and attach it to the defaultpress__fentent () Wordpress function . Like this.

4. INSERT CONTENT AUTOMATICALLY AFTER EACH POST


Problem.

Most blogs have a single.php file to display content after each post , but the trouble is: this content will not be displayed in the RSS feed. Hooks will help fix this problem.

Decision.

All the same - just copy the following code to the fucntions.php file .

  1. function insertFootNote ($ content) {
  2.         if (! is_feed () &&! is_home ()) {
  3.                 $ content. = "";
  4.                 $ content. = "

    Enjoyed this article?

    ";
  5.                 $ content. = "

    Subscribe to our  RSS feed and never miss a recipe!

    ";
  6.                 $ content. = "
";
  •         }
  •         return $ content;
  • }
  • add_filter ('the_content', 'insertFootNote');


  • Code explanation.

    The essence of the insertFootNote () function is simple: it only concatenates the desired text to the $ content variable , which stores the contents of the post.
    Then, we attach our insertFootNote () function to the_content () function .
    You see in line 2 this code:

    1. if (! is_feed () &&! is_home ()) {


    If you need the text to fall into the RSS feed, then replace the previous code with this:

    1. if (! is_home ()) {


    That's all.

    5. DISABLED MESSAGE WITH PLEASE UPDATE IN WORDPRESS CONTROL PANEL


    Problem.

    You can see information about the availability of the new version of Wordpress at the top of the dashboard. This is really a good thing, since the update closes the security holes and allows you to use the latest features of the engine. But if the blog is not yours personally, but is a project for any of the customers, then giving customers the opportunity to update themselves is not a good idea.

    Decision.

    Just paste the following code into the fucntions.php file .

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


    After you save the functions.php file , you will no longer see messages.

    Code explanation.

    To get started, make sure that the current user has sufficient administrator rights so that Wordpress can be updated. As soon as we are convinced of this, we create a couple of hooks that rewrite the rules for displaying messages in the dashboard.

    6. DISABLE AUTOMATIC POST STORAGE


    Problem.

    Wordpress periodically saves the post as it is introduced. This is a useful feature, but sometimes it is not required.

    Decision.

    In order to disable the autosave of the post, simply open the functions.php file and paste the following code into it.

    1. function disableAutoSave () {
    2.     wp_deregister_script ('autosave');
    3. }
    4. add_action ('wp_print_scripts', 'disableAutoSave');


    Code explanation.

    And again, nothing complicated: we just create a function that disables autosaving and binds it to the wp_print_scripts () Wordpress function .

    7. DELIVERING OF REPEATED CONTENT ON PAGES WITH COMMENTS


    Problem.

    Duplicate content is a fairly common SEO problem.
    The pagination system introduced in Wordpress version 2.7 does not solve this problem.
    To prevent duplicate content in the comments, we will use the rel = "canonical" attribute .

    Decision.

    Copy the following code and paste it into the functions.php file .

    1. function canonical_for_comments () {
    2. global $ cpage, $ post;
    3. if ($ cpage> 1):
    4. echo "\ n";
    5.    echo "
    6.    echo get_permalink ($ post-> ID);
    7.    echo "'/> \ n";
    8.  endif;
    9. }
    10.  
    11. add_action ('wp_head', 'canonical_for_comments');


    Code explanation.

    First, we create a function that adds to each page with comments, except the first, a link tag with the attribute rel = "canonical" . Then, attach this function to the Wordpress function wp_head () .

    8. GETTING POST OR PAGE AS A PHP VARIABLE


    Problem.

    Being able to get the current post or the whole page as a PHP variable is a really cool thing. Let's say you can replace some parts of the content with the str_replace () function or do something else with it.

    Decision.

    And again, nothing complicated. We do the same: insert the following code into the functions.php file .

    1. function callback ($ buffer) {
    2. // modify buffer here, and then return the updated code
    3. return $ buffer;
    4. }
    5.  
    6. function buffer_start () {
    7. ob_start ("callback");
    8. }
    9.  
    10. function buffer_end () {
    11. ob_end_flush ();
    12. }
    13.  
    14. add_action ('wp_head', 'buffer_start');
    15. add_action ('wp_footer', 'buffer_end');


    Code explanation.

    In order for this hack to work, three functions are needed:
    • callback () : this function returns the entire page as a $ buffer variable . You can modify it as you like, for example, using regular expressions;
    • buffer_start () : this function starts buffering. We attach it to the wp_head () function ;
    • buffer_end () : this function clears the buffer. We attach it to the wp_footer () function .


    9. USE HOOKS AND CRON FOR SCHEDULE EVENTS


    Problem.

    You probably already know that Wordpress can use scheduled events. For example, you can publish posts at a specific time set in advance. Using hooks and wp-cron , we can easily set a schedule for our own event. In the following example, we will force the blog to send us e-mail messages once every hour.

    Decision.

    Paste the following code into the functions.php file .

    1. if (! wp_next_scheduled ('my_task_hook')) {
    2. wp_schedule_event (time (), 'hourly', 'my_task_hook');
    3. }
    4.  
    5. add_action ('my_task_hook', 'my_task_function'); 
    6.  
    7. function my_task_function () {
    8. wp_mail ('you@yoursite.com ',' Automatic email ',' Hello, this is an automatically scheduled email from WordPress. ');
    9. }


    Code explanation.

    The first thing we will do, of course, is to create a function that will perform the required action. In this example, this function is called my_task_function () and it simply sends an email to the specified e-mail address.
    In order to schedule the execution of this function, we will use the wp_schedule_event () function . The last argument passed to it will be our hook, so we "hook" our function my_task_function () to my_task_hook .

    10. LIST OF ALL “KNOCKED” FUNCTIONS


    Problem.

    When something goes wrong, a list of all the “hooked” functions may come in handy.

    Decision.

    Like all previous code snippets, the next one also needs to be inserted into the functions.php file . Just remember to remove it after use. If you do not, then messages will appear after debugging.

    1. function list_hooked_functions ($ tag = false) {
    2.  global $ wp_filter;
    3.  if ($ tag) {
    4.   $ hook [$ tag] = $ wp_filter [$ tag];
    5.   if (! is_array ($ hook [$ tag])) {
    6.   trigger_error ("Nothing found for '$ tag' hook", E_USER_WARNING);
    7.   return
    8.   }
    9.  }
    10.  else {
    11.   $ hook = $ wp_filter;
    12.   ksort ($ hook);
    13.  }
    14.  echo '
      ';
    15.  foreach ($ hook as $ tag => $ priority) {
    16.   echo ">>>>> \ t $ tag";
    17.   ksort ($ priority);
    18.   foreach ($ priority as $ priority => $ function) {
    19.   echo $ priority;
    20.   foreach ($ function as $ name => $ properties) echo "\ t $ name";
    21.   }
    22.  }
    23.  echo '';
    24.  return
    25. }


    After you paste this code into the functions.php file , call the list_hooked_functions () function . She will show you a list of all the "hooked" functions.

    1. list_hooked_functions ();


    Code explanation.

    This code will figure out if the hook name is passed as an argument to the function. If transmitted, the name of the hook is displayed. You can also see hooks only for a specific function:

    1. list_hooked_functions ('wp_head');


    Also popular now: