WordPress Hooks: Actions and Filters - Usage Examples
WordPress hooks are pieces of code that interact with one another. They can modify WordPress's default behavior without touching the core files.?
WordPress has introduced two types of hooks: action hooks and filter hooks.
Action hooks
The action hooks are used to modify the default behavior of a specific WordPress function. It doesn't return any data to WordPress after completing the task.
Example 1.1 - after_setup_theme
Fires after the theme is loaded on the front end.
<?php
function wp_custom_theme_setup() {
// Allows themes to manage document title tag
add_theme_support( 'title-tag' );
// Enables post thumbnail support for a theme
add_theme_support( 'post-thumbnails' );
// Enable image, video, quote, and gallery support for a theme
add_theme_support( 'post-formats', array(
'image', 'video', 'quote', 'gallery'
) );
// Allows the use of HTML5 markup for the search forms, comment forms, comment lists
add_theme_support( 'html5', array(
'search-form', 'comment-form', 'comment-list',
) );
}
add_action( 'after_setup_theme', 'wp_custom_theme_setup' );
Example 1.2 - init
Fires after WordPress has finished loading but before any headers are sent.
function book_setup_post_type() {
$args = array(
'public' => true,
'label' => __( 'Books', 'textdomain' ),
'menu_icon' => 'dashicons-book',
);
register_post_type( 'book', $args );
}
add_action( 'init', 'book_setup_post_type' );
Example 1.3 - widgets_init
Fires after all default WordPress widgets have been registered.
Register a sidebar for a theme
function mytheme_widgets_init() {
register_sidebar( array(
'name' => __( 'Single Post Widgets', 'textdomain' ),
'id' => 'mytheme-single-post-widgets',
'description' => __( 'Widgets in this area will be shown under your single posts, before comments.', 'textdomain' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
}
add_action( 'widgets_init', 'mytheme_widgets_init' );
Example 1.4 - wp_enqueue_scripts
Fires when scripts and styles are enqueued.
The 'wp_enqueue_scripts’ hook is used to enqueue scripts and styles that are meant to appear on the front end.
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script('custom-script', '/path/to/custom-script.js', array('custom-script'), null, true);
});
Example 1.5 - admin_bar_menu
Loads all necessary admin bar items.
This is the hook used to add, remove, or manipulate admin bar items.
Add date and time to the right side of the admin bar.
add_action( 'admin_bar_menu', 'adminbar_date_time', 500 );
function adminbar_date_time ( WP_Admin_Bar $wp_admin_bar ) {
$parent_slug = 'adminbar-date-time';
$local_time = date( 'Y-m-d, g:i a', current_time( 'timestamp', 0 ) );
$wp_admin_bar->add_menu( array(
'id' => $parent_slug,
'parent' => 'top-secondary',
'group' => null,
'title' => $local_time,
'href' => admin_url( '/options-general.php' ),
) );
}
Example 1.6 - admin_enqueue_scripts
Fires when enqueuing scripts for all admin pages.
'admin_enqueue_scripts’ is the proper hook to use when enqueuing scripts and styles that are meant to be used in the administration panel.
function enqueue_custom_admin_script( ) {
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'myscript.js', array(), '1.0' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_custom_admin_script' );
Example 1.7 - admin_notices
Prints admin screen notices.
function sample_admin_notice__success() {
?>
<div class="notice notice-success is-dismissible">
<p><?php _e( 'Done!', 'sample-text-domain' ); ?></p>
</div>
<?php
}
add_action( 'admin_notices', 'sample_admin_notice__success' );
Example 1.8 - wp_dashboard_setup
Fires after core widgets for the admin dashboard have been registered.
Add a dashboard widget?
function wpdocs_add_dashboard_widgets() {
wp_add_dashboard_widget( 'dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function' );
}
add_action( 'wp_dashboard_setup', 'wpdocs_add_dashboard_widgets' );
function dashboard_widget_function( $post, $callback_args ) {
esc_html_e( "Hello World, this is my first Dashboard Widget!", "textdomain" );
}
Remove multiple dashboard widgets?
add_action('wp_dashboard_setup', 'remove_dashboard_widgets');
function remove_dashboard_widgets () {
// Remove various dashboard widgets
remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' ); //Quick Press widget
remove_meta_box( 'dashboard_recent_drafts', 'dashboard', 'side' ); //Recent Drafts
}
Example 1.9 - save_post
Fires once a post has been saved.
The following code snippets will send an email every time a post or page is updated on your website.
function my_project_updated_send_email( $post_id ) {
// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) ) {
return;
}
$post_title = get_the_title( $post_id );
$post_url = get_permalink( $post_id );
$subject = 'A post has been updated';
$message = "A post has been updated on your website:\n\n";
$message .= $post_title . ": " . $post_url;
// Send email to admin.
wp_mail( '[email protected]', $subject, $message );
}
add_action( 'save_post', 'my_project_updated_send_email' );
领英推荐
Example 1.10 - wp_head
Prints scripts or data in the head tag on the front end.
function hook_css() {
?>
<style>
.wp_head_example {
background-color : #f1f1f1;
}
</style>
<?php
}
add_action('wp_head', 'hook_css');
Filter hooks
The filter hooks are used to modify the default behavior of a specific wordpress function. After completing the task, it returns some data to wordpress.
Example 2.1 - body_class
Filters the list of CSS body class names for the current post or page.
You can add additional body classes by filtering the ‘body_class’ hook.
add_filter( 'body_class', function( $classes ) {
return array_merge( $classes, array( 'class-name' ) );
} );
Remove an existing body class by un-setting the key from the $classes array.
// Removes a class from the body_class array.
add_filter( 'body_class', function( $classes ) {
if ( isset( $classes['class-to-remove'] ) ) {
unset( $classes['class-to-remove'] );
}
return $classes;
} );
Example 2.2 - comment_form_fields
Filters the comment form fields, including the textarea.
Move the comment text field to the bottom.
function prefix_move_comment_field_to_bottom( $fields ) {
$comment_field = $fields['comment'];
unset( $fields['comment'] );
$fields['comment'] = $comment_field;
return $fields;
}
add_filter( 'comment_form_fields', 'prefix_move_comment_field_to_bottom', 10, 1 );
Example 2.3 - excerpt_length
Filters the maximum number of words in a post excerpt. Default excerpt length is 55.
function theme_slug_excerpt_length( $length ) {
if ( is_admin() ) {
return $length;
}
// Change the excerpt length to 50 words.
return 50;
}
add_filter( 'excerpt_length', 'theme_slug_excerpt_length', 999 );
Example 2.4 - get_the_archive_title
Filters the archive title.
Using the hook to get rid of archive “label”:
function my_theme_archive_title( $title ) {
if ( is_category() ) {
$title = single_cat_title( '', false );
} elseif ( is_tag() ) {
$title = single_tag_title( '', false );
} elseif ( is_author() ) {
$title = '<span class="vcard">' . get_the_author() . '</span>';
} elseif ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
} elseif ( is_tax() ) {
$title = single_term_title( '', false );
}
return $title;
}
add_filter( 'get_the_archive_title', 'my_theme_archive_title' );
Example 2.5 - get_comment_date
Filters the returned comment date.
function custom_comment_date( $date, $d, $comment ) {
return mysql2date( 'F jS, Y', $comment->comment_date );
}
add_filter( 'get_comment_date', 'custom_comment_date', 10, 3);
Example 2.6 - login_redirect
Filters the login redirect URL.
function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if ( in_array( 'administrator', $user->roles ) ) {
// redirect them to the default place
return $redirect_to;
} else {
return home_url();
}
} else {
return $redirect_to;
}
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
Example 2.7 - upload_mimes
Filters the list of allowed mime types and file extensions.
function my_custom_mime_types( $mimes ) {
// New allowed mime types.
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
$mimes['doc'] = 'application/msword';
// Optional. Remove a mime type.
unset( $mimes['exe'] );
return $mimes;
}
add_filter( 'upload_mimes', 'my_custom_mime_types' );
Example 2.8 - upload_size_limit
Filters the maximum upload size allowed in php.ini.
function filter_site_upload_size_limit( $size ) {
// Set the upload size limit to 10 MB for users lacking the 'manage_options' capability.
if ( ! current_user_can( 'manage_options' ) ) {
// 10 MB.
$size = 1024 * 10000;
}
return $size;
}
add_filter( 'upload_size_limit', 'filter_site_upload_size_limit', 20 );
Example 2.9 - excerpt_more
Filters the string in the “more” link displayed after a trimmed excerpt.
function my_theme_excerpt_more( $more ) {
// Change the excerpt more string
return 'read more';
}
add_filter( 'excerpt_more', 'my_theme_excerpt_more' );
Example 2.10 - show_admin_bar
Filters whether to show the admin bar.
This would hide the toolbar for all users except administrators.
add_filter( 'show_admin_bar' , 'my_function_admin_bar');
function my_function_admin_bar($show_admin_bar) {
return ( current_user_can( 'administrator' ) ) ? $show_admin_bar : false;
}