
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:
')
- 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:
- 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:
- 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 ) ;
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!
- add_filter ( 'body_class' , 'browser_class_class' ) ;
- 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 ;
- }
After you save the file, the function will automatically add a CSS class corresponding to the user’s browser for the
body tag:
- < 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.
- add_filter ( 'default_content' , 'my_editor_content' ) ;
- function my_editor_content ( $ content ) {
- $ content = "If you enjoyed this post, make sure you subscribe." ;
- return $ content ;
- }
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.
- 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' ) ;
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:
- if ( ! is_feed ( ) && ! is_home ( ) ) {
If you need the text to be in the RSS feed, then replace the previous code with this one:
- 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.
- 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;" ) ) ;
- }
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.
- function disableAutoSave ( ) {
- wp_deregister_script ( 'autosave' ) ;
- }
- 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.
- function canonical_for_comments ( ) {
- global $ cpage , $ post ;
- if ( $ cpage > 1 ) :
- echo " \ n " ;
- echo "<link rel = 'canonical' href = '" ;
- echo get_permalink ( $ post -> ID ) ;
- echo "'/> \ n " ;
- endif ;
- }
- 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.
- function callback ( $ buffer ) {
- // modify buffer here
- return $ buffer ;
- }
- function buffer_start ( ) {
- ob_start ( "callback" ) ;
- }
- function buffer_end ( ) {
- ob_end_flush ( ) ;
- }
- add_action ( 'wp_head' , 'buffer_start' ) ;
- add_action ( 'wp_footer' , 'buffer_end' ) ;
Explanation of the code.
In order for this hack to work, three functions are needed:
- callback () : this function returns the entire page as a variable $ buffer . You can modify it as you like, for example, using regular expressions;
- buffer_start () : this function starts buffering. We add it to the wp_head () function;
- buffer_end () : this function clears the buffer. We add it to the wp_footer () function.
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.
- 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.' ) ;
- }
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.
- 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 /> & gt; & gt; & gt; & gt; & gt; \ t <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 ;
- }
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.
- 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:
- list_hooked_functions ( 'wp_head' ) ;