February 5, 2020

Essential WordPress Hooks Every Developer Should Know (with Practical Examples) – Part 2

Handling WordPress Initialization

This hook is init. Simply put, it’s triggered after WordPress initialization — that’s why this hook might be the most popular WordPress action hook ever — because you can hook almost anything to it.

Changing Some Default Rewrite Rules

<?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';
}
?>

Pretty cool, right?

Letting IE Use the Latest Rendering Engine

The X-UA-Compatible meta tag allows you to tell Internet Explorer to use a specific rendering engine. If you set it to "edge", IE will use its latest engine.
However, if you use the Google Chrome Frame, this tag may fail HTML validation.

Luckily, you’re not limited to using a <meta> tag — you can set this via HTTP headers using the send_headers hook:

<?php
 
add_action( 'send_headers', 'send_headers_example' );
 
function send_headers_example() {
    header( 'X-UA-Compatible: IE=edge,chrome=1' );
}
?>

Flushing Rewrite Rules After Theme Switch

Here’s a simple example:
If your new theme uses custom post types, how do you refresh the rewrite rules after switching to it?

Well, here’s the code:

<?php
 
add_action( 'after_switch_theme', 'after_switch_theme_example' );
 
function after_switch_theme_example() {
    flush_rewrite_rules();
}
?>

Pretty easy, right?

For some reason, I couldn’t get flush_rewrite_rules() to work properly when hooked into after_switch_theme.
If you know why, please let us know in the comments — thanks!

Displaying the Number of Attachments Per Post

Suppose you want to know how many attachments each post has — maybe because you require exactly 10 images per post as a gallery.

Rather than counting manually in the Media Library, you can display it directly:





<?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;
        }
    }
}
?>