The previous part of our series was the "introduction" to the world of WordPress actions. In this tutorial, we're going to start reviewing 50 selected actions by explaining what they do and see an example for each action.
So, without further ado, here's the first batch of our 50 actions!
Handling the WordPress Initialization
This action, in short, is fired off right after everything's ready except the headers. And that's why this action is probably the most popular WordPress action of all time – because you can hook almost anything to it.
Changing a Few Default Rewrite Rules
As a Turkish WordPress user, I find it odd (and kind of frustrating) that WordPress doesn't allow us change the URL bases for author pages, search results, or paginated archive pages in the admin panel.
The code snippet below, though, helps me with this issue:
<?php add_action( 'init', 'init_example' ); function init_example() { global $wp_rewrite; $wp_rewrite->author_base = 'profile'; $wp_rewrite->search_base = 'find'; $wp_rewrite->pagination_base = 'p'; } ?>
Cool, huh? (Of course, I replaced the Turkish words with 'profile', 'find' and 'p' to make it clear.)
Sending HTTP Headers
This doesn't need an introduction as its name explains itself: This handy little action allows us to set the HTTP headers to send!
Make Internet Explorer Use the Latest Rendering Engine
The X-UA-Compatible
meta tag makes Internet Explorer use the specified rendering engine for the web page. If you set it to "edge"
, Internet Explorer will use the latest rendering engine; however, it breaks HTML validation if used with the Google Chrome Frame.
Luckily, we're not limited with the <meta>
tag usage: We can use HTTP headers, too. And the send_headers
action is perfect for the job:
<?php add_action( 'send_headers', 'send_headers_example' ); function send_headers_example() { header( 'X-UA-Compatible: IE=edge,chrome=1' ); } // Example Source: http://codex.wordpress.org/Plugin_API/Action_Reference/send_headers ?>
Switching Themes
If you want to run some errands after you switch themes in WordPress, you can count on the after_switch_theme
action.
Flushing the Rewrite Rules After Switching a Theme
Let's do an easy one: How do you flush rewrite rules after switching to a new theme, because the new theme has new custom post types?
Well, you use the code below:
<?php add_action( 'after_switch_theme', 'after_switch_theme_example' ); function after_switch_theme_example() { flush_rewrite_rules(); } // Example Source: http://wpdevsnippets.com/flush-rewrite-rules/ ?>
Easy, right?
For some reason, I couldn't make it work by hooking the flush_rewrite_rules()
function to the after_switch_theme
action and I couldn't find out why – if you have the answer, enlighten us in the comments.
Adding Custom Columns to the Posts List
This handy little action allows us to create additional columns to the posts list in the "All Posts" admin page.
Display Each Post's Attachment Count in a Column
Imagine that you need to see how many files you attached to each of your posts because, say, you want to double-check that you attached 10 gallery images for every post of yours. Instead of counting them one by one in the Media Library, you can add an extra column to the listing in the "All Posts" page like this:
<?php add_filter( 'manage_posts_columns', 'manage_posts_columns_example', 5 ); add_action( 'manage_posts_custom_column', 'manage_posts_custom_column_example', 5, 2 ); function manage_posts_columns_example( $columns ) { $columns['post_attachments'] = __( 'Attached', 'theme-name' ); return $columns; } function manage_posts_custom_column_example( $column_name, $post_id ) { if( 'post_attachments' == $column_name ) { $attachments = get_children( array( 'post_parent' => $post_id ) ); $count = count( $attachments ); if( $count != 0 ) { echo $count; } } } // Example Source: http://wpsnipp.com/index.php/functions-php/display-post-attachment-count-in-admin-column/ ?>
Granted, this is an example for a very spesific scenario. But remember that you saw it on Tuts+ Code – you never know when you'll need it!
Working With the <head>
of Admin Pages
From time to time, we might need to inject things into the <head>
s of the pages of our administration panel. And the admin_head
action does exactly that!
Displaying a Different Favicon in the Back End
This quick and simple example demonstrates how to inject the necessary HTML code for a "favicon" into your admin panel's <head>
with ease:
<?php add_action( 'admin_head', 'admin_head_example' ); function admin_head_example() { echo '<link rel="shortcut icon" type="image/x-icon" href="' . get_bloginfo('template_directory') . '/images/admin-favicon.ico" />'; } // Example Source: http://wpdevsnippets.com/wp-admin-custom-favicon/ ?>
Place an admin-favicon.ico
file inside the /images/
folder in your theme and you're good to go!
Injecting Code Into the wp_footer()
Function
This action is called when the function with the same, wp_footer()
name is run. You can use it to customize the output of the function.
Displaying a Quick Performance Report for Admins
Want to see a quick report of how many queries your pages run and how much memory they use? These bits of code will help you with that:
<?php add_action( 'wp_footer', 'wp_footer_example' ); function wp_footer_example() { $stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory', get_num_queries(), timer_stop( 0, 3 ), memory_get_peak_usage() / 1024 / 1024 ); if( current_user_can( 'manage_options' ) ) { echo "<!-- {$stat} -->"; } } // Example Source: http://wordpress.stackexchange.com/a/1866 ?>
Now you will see a commented out piece of information about your queries in the source code of your web pages. Don't worry: Non-administrators won't see this.
Handling the Enqueuing of Frontend Scripts
This is one of the fundamental need-to-know actions if you're working with themes: The wp_enqueue_scripts
action handles the process of enqueuing scripts and styles in the front-end.
The Correct Usage of the wp_enqueue_script()
Function
There are many ways to enqueue scripts and styles in the front-end, but there's only one correct way to do it:
<?php add_action( 'wp_enqueue_scripts', 'wp_enqueue_scripts_example' ); function wp_enqueue_scripts_example() { // you can enqueue scripts... wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/scripts/my-script.js' ); // ...and styles, too! wp_enqueue_style( 'my-style', get_stylesheet_directory_uri() . '/styles/my-style.css' ); } ?>
Creating Admin Page Notices
The action admin_notices
is responsible for all the warnings, errors or other messages displayed in the header of admin pages. You can use it to display your own messages, too.
Warning Logged-in Users About Website Maintenance
Suppose you're moving servers and you need to inform your authors about the situation: They shouldn't post anything! You can lock down the entire admin panel to non-admins, or you can display a simple warning message like this:
<?php add_action( 'admin_notices', 'admin_notices_example' ); function admin_notices_example() { echo '<div class="error"> <p>We are performing website maintenance. Please don\'t make any changes in your posts until further notice!</p> </div>'; } // Example Source: http://wpsnippy.com/show-notification-message-wordpress-admin-pages/ ?>
We used the "error" class here. If you want a green border (which means more like a "success" message), you can use the "updated" class.
Handling the Initialization of Widgets
WordPress widgets are an excellent system that allows us developers to create and edit parts of our websites. And the widgets_init
action lets us modify the behavior of widgets if necessary.
Prevent Loading Default WordPress Widgets
For some reason, you might want to disable the usage of default WordPress widgets altogether. If that's the case, the code snippet below will help you completely remove those widgets from your WordPress installation:
<?php add_action( 'widgets_init', 'widgets_init_example' ); function widgets_init_example() { unregister_widget( 'WP_Widget_Pages' ); unregister_widget( 'WP_Widget_Calendar' ); unregister_widget( 'WP_Widget_Archives' ); unregister_widget( 'WP_Widget_Links' ); unregister_widget( 'WP_Widget_Meta' ); unregister_widget( 'WP_Widget_Search' ); unregister_widget( 'WP_Widget_Text' ); unregister_widget( 'WP_Widget_Categories' ); unregister_widget( 'WP_Widget_Recent_Posts' ); unregister_widget( 'WP_Widget_Recent_Comments' ); unregister_widget( 'WP_Widget_RSS' ); unregister_widget( 'WP_Widget_Tag_Cloud' ); } ?>
Of course, you can comment out or remove the lines to allow some widgets to load.
Deleting WordPress Users
Need to do stuff each time a user is deleted? The delete_user
is your guy: It's triggered after a user gets deleted.
Emailing the Poor Guy After Deleting His Account
If you have a website that occasionally attracts bad people and you need to delete users frequently, you might want to consider letting them know that their user accounts are deleted. The code snippet below will help you:
<?php add_action( 'delete_user', 'delete_user_example' ); function delete_user_example( $user_id ) { global $wpdb; $user_obj = get_userdata( $user_id ); $email = $user_obj->user_email; $headers = 'From: ' . get_bloginfo( 'name' ) . ' <' . get_bloginfo( 'admin_email' ) . '>' . "\r\n"; $subject = 'You are being deleted, brah'; $message = 'Your account at ' . get_bloginfo( 'name' ) . ' has been deleted because of your totally uncool behaviors.'; wp_mail( $email, $subject, $message, $headers ); } // Example Source: http://codex.wordpress.org/Plugin_API/Action_Reference/delete_user ?>
If you want, you can replace the $subject
and $message
variables with more formal messages.
Wrapping Up for Today
We went through 10 of 50 actions in this article. I hope you liked and learned new things from it. See you in the next one!
I want to hear your thoughts, too. What do you think about these actions? Post your comments below; and if you liked the article, don't forget to share it!
Comments