📜 ⬆️ ⬇️

10 useful hooks for wordpress

image
About what hooks are in Wordpress and how to use them there. Article of a young Wordpress-specialist, owner of the site www.wprecipes.com , from Belgium.

INTRODUCTION


Hooks are very useful chips in wordpress. They allow, as it were, to “put” a user-defined function “on the hook” of the existing function, thereby allowing to modify Wordpress functionality without making changes to the engine core files. In this article, we present you 10 particularly useful, ready-to-use WordPress hooks, with examples and explanations of their sources.

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 were named by the developers as the kernel files — they are necessary for Wordpress to work properly.
But changing kernel files is a bad idea: it can create a security breach in a blog. Also, all modifications will disappear as soon as you update the engine to the new version.
However, an extension of the functionality is still necessary. For this, the developers invented the Plugin API.
Hooks are one of the main blocks for building plugins. Almost every plugin plugin uses hooks to extend Wordpress functionality.

HOW TO USE HOOKS IN YOUR BLOG


Until you have written your plugin, you must write 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 user-defined function to the engine core function:
')
  1. add_action ( 'publish_post' , 'myCustomFunction' ) ;


In this example, we connected the user 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. DISABLE AUTOMATIC FORMATTING IN WORDPRESS


Problem.

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

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. foreach ( $ pieces as $ piece ) {
  7. if ( preg_match ( $ pattern_contents , $ piece , $ matches ) ) {
  8. $ new_content . = $ matches [ 1 ] ;
  9. } else {
  10. $ new_content . = wptexturize ( wpautop ( $ piece ) ) ;
  11. }
  12. }
  13. return $ new_content ;
  14. }
  15. remove_filter ( 'the_content' , 'wpautop' ) ;
  16. remove_filter ( 'the_content' , 'wptexturize' ) ;
  17. add_filter ( 'the_content' , 'my_formatter' , 99 ) ;


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

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



Explanation of the code.

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 the execution of our function whenever the the_content () function is called .
In order to disable auto-formatting, we used the remove_filter () function.

2. DETERMINING A VISITOR BROWSER WITH HOOKS


Problem.

Cross-browser compatibility is the most common problem in web development. You will save a lot of time and nerves if you can identify the browser of the user who has come to your blog, and then creating 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 - everything is ready!

  1. add_filter ( 'body_class' , 'browser_class_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. if ( $ is_lynx ) $ classes [ ] = 'lynx' ;
  5. elseif ( $ is_gecko ) $ classes [ ] = 'gecko' ;
  6. elseif ( $ is_opera ) $ classes [ ] = 'opera' ;
  7. elseif ( $ is_NS4 ) $ classes [ ] = 'ns4' ;
  8. elseif ( $ is_safari ) $ classes [ ] = 'safari' ;
  9. elseif ( $ is_chrome ) $ classes [ ] = 'chrome' ;
  10. elseif ( $ is_IE ) $ classes [ ] = 'ie' ;
  11. else $ classes [ ] = 'unknown' ;
  12. if ( $ is_iphone ) $ classes [ ] = 'iphone' ;
  13. return $ classes ;
  14. }


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

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


Explanation of the code.

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 take the value true . This is why we create the browser_body_class () function. After that we attach it to the wordpress function body_class () .

3. DEFINITION OF TEXT BY 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 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 to hook. Copy the code into the file functions.php and see how it works.

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


Explanation of the code.

This code, though simple, is very powerful. Simply create a function that returns the required text (in this example, we define text that asks visitors for a subscription to the RSS feed), and attach it to the Wordpress function default_content () . Like this.

4. INSERT CONTENT AUTOMATICALLY AFTER EACH POST


Problem.

In most blogs for displaying content after each post file is single.php , 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 . = "<div class = 'subscribe'>" ;
  4. $ content . = "<h4> Enjoyed this article? </ h4>" ;
  5. $ content . = "<p> Subscribe to our <a href='http://feeds2.feedburner.com/WpRecipes'> RSS feed </a> and never miss a recipe! </ p>" ;
  6. $ content . = "</ div>" ;
  7. }
  8. return $ content ;
  9. }
  10. add_filter ( 'the_content' , 'insertFootNote' ) ;


Explanation of the code.

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

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


If you need the text to be in the RSS feed, then replace the previous code with this one:

  1. if ( ! is_home ( ) ) {


That's all.

5. DISABLE THE MESSAGE WITH THE REQUEST TO UPDATE IN THE WORDPRESS CONTROL PANEL


Problem.

You can see information about the availability of a new version of Wordpress at the top of the dashboard. This is really a good thing, because the update closes 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 one of the clients, then letting the clients 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 the message.

Explanation of the code.

First, make sure that the current user has sufficient administrator privileges so that Wordpress can be updated. Once we are convinced of this, create a couple of hooks that rewrite the rules for displaying messages in the dashboards.

6. DISABLE POSTS AUTO SAVING


Problem.

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

Decision.

To disable autosave 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' ) ;


Explanation of the code.

Again, nothing complicated: we simply create a function that disables autosave and binds it to the Wordpress function wp_print_scripts () .

7. GET RID 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 "<link rel = 'canonical' href = '" ;
  6. echo get_permalink ( $ post -> ID ) ;
  7. echo "'/> \ n " ;
  8. endif ;
  9. }
  10. add_action ( 'wp_head' , 'canonical_for_comments' ) ;


Explanation of the code.

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

8. GETTING A POST OR PAGE AS A PHP VARIABLE


Problem.

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

Decision.

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

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


Explanation of the code.

In order for this hack to work, three functions are needed:


9. USE HUKI AND CRON FOR EVENTS BY SCHEDULE


Problem.

You probably already know that Wordpress can use events on a schedule. For example, you can publish posts at a specific, predetermined time. Using hooks and wp-cron , we can easily set the schedule for our own event. In the following example, we will force the blog to send us emails 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. add_action ( 'my_task_hook' , 'my_task_function' ) ;
  5. function my_task_function ( ) {
  6. wp_mail ( 'you@yoursite.com' , 'Automatic email' , 'Hello, this is an automatically scheduled email from WordPress.' ) ;
  7. }


Explanation of the code.

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 final argument passed to it is our hook, so we “hook” our function my_task_function () to my_task_hook .

10. LIST OF ALL “SWEET” FUNCTIONS


Problem.

When something goes wrong, a list of all the "hooked" functions may be useful.

Decision.

Like all previous code snippets, the following should also be inserted into the functions.php file. Just remember to remove it after use. If you do not do this, 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 '<pre>' ;
  15. foreach ( $ hook as $ tag => $ priority ) {
  16. echo "<br /> & gt; & gt; & gt; & gt; & gt; \ t <strong> $ tag </ strong> <br />" ;
  17. ksort ( $ priority ) ;
  18. foreach ( $ priority as $ priority => $ function ) {
  19. echo $ priority ;
  20. foreach ( $ function as $ name => $ properties ) echo " \ t $ name <br />" ;
  21. }
  22. }
  23. echo '</ pre>' ;
  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 ( ) ;


Explanation of the code.

This code determines if the name of the hook 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' ) ;

Source: https://habr.com/ru/post/67680/


All Articles