March 10, 2020

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

Filter Default Gallery Styles

WordPress usually loads predefined CSS when using the shortcode. However, you can customize this behavior through the use_default_gallery_style filter hook.

Example: Disable Default Gallery Styles

If you have already defined gallery styles in your theme’s style.css file and do not want WordPress to load its default styles, you can disable them using the following code:

<?php
add_filter( 'use_default_gallery_style', '__return_false' );
?>

Now WordPress will no longer automatically add a <style> tag for the shortcode.

Filter Attachment URLs

You can use the wp_get_attachment_url filter hook to modify attachment URLs.

Example: Prevent “Mixed Content” Warnings

If your website uses SSL, the wp_get_attachment_url() function may still return http links, causing mixed content warnings. You can prevent this with the following code:

<?php
add_filter( 'wp_get_attachment_url', 'wp_get_attachment_url_example' );

function wp_get_attachment_url_example( $url ) {
    $http  = site_url( false, 'http'  );
    $https = site_url( false, 'https' );

    if ( $_SERVER['HTTPS'] === 'on' ) {
        return str_replace( $http, $https, $url );
    } else {
        return $url;
    }
}
?>

Set Default Email Content Type

By default, the wp_mail() function sends emails in text/plain. You can change this using the wp_mail_content_type filter hook.

Example: Send Emails in HTML Format

<?php
add_filter( 'wp_mail_content_type', 'wp_mail_content_type_example' );

function wp_mail_content_type_example( $content_type ) {
    return 'text/html';
}
?>

Save the Commenter’s Real IP Address

WordPress stores the IP address of commenters. You can modify how the IP is saved using the pre_comment_user_ip filter hook.

Example: Save the Real IP Address Behind Proxies

<?php
add_filter( 'pre_comment_user_ip', 'pre_comment_user_ip_example' );

function pre_comment_user_ip_example() {
    $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
    if ( !empty( $_SERVER['X_FORWARDED_FOR'] ) ) {
        $X_FORWARDED_FOR = explode( ',', $_SERVER['X_FORWARDED_FOR'] );
        $REMOTE_ADDR = trim( $X_FORWARDED_FOR[0] );
    } elseif ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
        $HTTP_X_FORWARDED_FOR = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
        $REMOTE_ADDR = trim( $HTTP_X_FORWARDED_FOR[0] );
    }
    return preg_replace( '/[^0-9a-f:\., ]/si', '', $REMOTE_ADDR );
}
?>

Modify the Number of Post Revisions

WordPress saves post revisions by default. To modify this behavior, you can either change the WP_POST_REVISIONS constant in wp-config.php or use the wp_revisions_to_keep filter hook.

Example: Disable Revisions for a Specific Post Type

<?php
add_filter( 'wp_revisions_to_keep', 'wp_revisions_to_keep_example', 10, 2 );

function wp_revisions_to_keep_example( $num, $post ) {
    if ( 'event' == $post->post_type ) {
        return 0;
    }
    return $num;
}
?>

Customize the Shortcode

You can modify the output of the shortcode using the img_caption_shortcode filter hook.

Example: Use HTML5 <figure> and <figcaption>

<?php
add_filter( 'img_caption_shortcode', 'img_caption_shortcode_example', 10, 3 );

function img_caption_shortcode_example( $empty, $attr, $content ) {
    $attr = shortcode_atts( array(
        'id'      => '',
        'align'   => 'alignnone',
        'width'   => '',
        'caption' => ''
    ), $attr );

    if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
        return '';
    }

    $id_attr = $attr['id'] ? 'id="' . esc_attr( $attr['id'] ) . '" ' : '';

    $output = '<figure ' . $id_attr . 'class="caption ' . esc_attr( $attr['align'] ) . '" style="max-width: ' . (10 + (int) $attr['width']) . 'px;">';
    $output .= do_shortcode( $content );
    $output .= '<figcaption>' . $attr['caption'] . '</figcaption>';
    $output .= '</figure>';

    return $output;
}
?>

Add Custom CSS Classes to Posts

WordPress provides a post_class filter to add custom CSS classes to post elements.

Example: Add a Special Class to the First Post

<?php
add_filter( 'post_class', 'post_class_example' );

function post_class_example( $classes ) {
    global $wp_query;
    if ( 0 === $wp_query->current_post ) {
        $classes[] = 'first-post';
    }
    return $classes;
}
?>

This helps you style the first post without relying on the CSS :first pseudo-class, improving browser compatibility.

Add Custom Fields to Attachments

Attachments in WordPress are similar to a custom post type. You can use the attachment_fields_to_edit filter to extend the attachment edit screen.

Example: Add a License Field to Uploaded Images

<?php
add_filter( 'attachment_fields_to_edit', 'attachment_fields_to_edit_example', 10, 2 );

function attachment_fields_to_edit_example( $form_fields, $post ) {
    $field_value = get_post_meta( $post->ID, 'license', true );
    $form_fields['license'] = array(
        'value' => $field_value ? $field_value : '',
        'label' => __( 'License' ),
        'helps' => __( 'Specify the license type used for this image' )
    );
    return $form_fields;
}

add_action( 'edit_attachment', 'save_new_attachment_field' );

function save_new_attachment_field( $attachment_id ) {
    $license = $_REQUEST['attachments'][$attachment_id]['license'];
    if ( isset( $license ) ) {
        update_post_meta( $attachment_id, 'license', $license );
    }
}
?>

Change the Length of Auto-Generated Excerpts

By default, WordPress excerpts are limited to 55 words. You can adjust this using the excerpt_length filter.

Example: Set Excerpt Length to 15 Words

<?php
add_filter( 'excerpt_length', 'excerpt_length_example' );

function excerpt_length_example( $length ) {
    return 15;
}
?>

Customize Bulk Actions in the Admin Panel

The WordPress admin dashboard includes bulk action dropdowns for posts, pages, users, etc. You can modify these options with specific hooks.

Example: Disable “Move to Trash” for Posts

<?php
add_filter( 'bulk_actions-edit-post', 'bulk_actions_edit_post_example' );

function bulk_actions_edit_post_example( $actions ) {
    unset( $actions['trash'] );
    return $actions;
}
?>