In the previous parts of this series, we went through 30 WordPress filters. In this tutorial, we're going to see another batch of them and do examples with each.
Let's begin!
Filtering the Search Query
Searching is one of the most important features of WordPress (and it has stayed kind of primitive, for some reason). With the posts_search
filter, you can monkey with the search SQL.
Example: Including Password Protected Posts in Search Results
Let's say you use posts for your clients' information and you set passwords for each post and send the password for your client.
To let the clients search amongst the posts and find their own page, you can use the code snippet below to enable visitors find password-protected posts within the search results:
<?php add_filter( 'posts_search', 'posts_search_example' ); function posts_search_example( $search ) { global $wpdb; if( !is_user_logged_in() ) { $pattern = " AND ({$wpdb->prefix}posts.post_password = '')"; $search = str_replace( $pattern, '', $search ); } return $search; } // Example source: http://wpsnipp.com/index.php/functions-php/include-password-protected-posts-in-search-results/ ?>
If the users of your blog are registered, you don't have to use the code above: They can search through password-protected posts as long as they're logged in – but of course, they still can't see the content unless they enter the password.
Setting Compression Quality for Uploaded Images
By default, WordPress tries to compress your images while resizing for the defined image sizes. With the wp_editor_set_quality
filter, you can change or disable the compression rate.
Example: Prevent WordPress from Compressing & Distorting Your Images
Image compression in PHP results in subtle distortions which can only be seen by keen eyes for details. If your website have an sharp-eyed audience (Designers, maybe?) and don't want WordPress to use this compression algorithm, you can use the code below to disable compression and avoid distortion:
<?php add_filter( 'wp_editor_set_quality', 'wp_editor_set_quality_example' ); function wp_editor_set_quality_example( $quality ) { return 100; } ?>
Filtering the Text Widget
Default widgets in WordPress has their own filters. The widget_text
filter is the filter of, you guessed it, the Text widget.
Example: Enable Shortcodes for the Text Widget
It's kind of annoying that WordPress doesn't let us use shortcodes in the text widget by default. Thanks for its filter, though, we can enable shortcodes within the widget:
<?php add_filter( 'widget_text', 'do_shortcode' ); ?>
...wait, no function to hook? Actually, there is: It's a core function named do_shortcode()
which you may have heard of. Since there's already a function to hook to the filter, we don't have to write another one.
Filtering the Feed Content
As you can filter the post content with the_content
, you can tamper with the feed items, too, with the the_content_feed
filter.
Example: Inserting Post Thumbnails to Feed Items
This example is one of my favorites among all the examples in this series: Adding the much-needed post thumbnail to your feed items!
<?php add_filter( 'the_content_feed', 'the_content_feed_example' ); function the_content_feed_example( $content ) { $featured_image = ''; $featured_image = get_the_post_thumbnail( get_the_ID(), 'thumbnail', array( 'style' => 'float:left;margin-right:.75em;' ) ); $content = get_the_excerpt() . ' <a href="'. get_permalink() .'">' . __( 'Read More' ) . '</a>'; if( '' != $featured_image ) $content = '<div>' . $featured_image . $content . '<br style="clear:both;" /></div>'; return $content; } ?>
If you want the thumbnails to be displayed on the right of the excerpt, simply change 'float:left;margin-right:.75em;'
with 'float:right;margin-left:.75em;'
.
Changing Buttons from the Visual Editor
WordPress comes with TinyMCE, an advanced WYSIWYG editor that we use while we write our posts. With the mce_buttons
filter, we can change the first line of buttons in that editor.
Example: Remove Unwanted Buttons from the Visual Editor
If you run a multi-author blog and you don't want your authors to use specific buttons in the visual editor, you can remove some of the buttons (or all of them) with the code below:
<?php add_filter( 'mce_buttons', 'mce_buttons_example' ); function mce_buttons_example( $buttons ) { $remove_array = array( 'strikethrough', 'blockquote', 'hr', 'alignleft', 'aligncenter', 'alignright', 'wp_more', 'wp_adv' ); // full list (WP version 3.9) // 'bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'hr', 'alignleft', 'aligncenter', 'alignright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' foreach( $remove_array as $remove ) { if ( ( $key = array_search( $remove, $buttons ) ) !== false ) unset( $buttons[ $key ] ); } return $buttons; } ?>
Note that it doesn't disable the usage of the things you remove – it just removes the buttons.
As I said, this filter deals with the first line of the buttons in the visual editor. For the second line (the "advanced buttons"), there is another filter named mce_buttons_2
and there are two additional filters for two emtpy lines: mce_buttons_3
and mce_buttons_4
.
Excluding Terms from Lists
There might be times when you need to "exclude" a term from every single term list in your website. This little filter allows us to do exactly what its name suggests.
Example: Excluding the Categories Your Plugin Created
Imagine you built a plugin that needs to create two categories named "Favorited-MyPlugin" and "Hated-MyPlugin". It would look ugly if the tags were listed in the categories lists, so you need to hide them from the lists. Here's how you do it:
<?php add_filter( 'list_terms_exclusions', 'list_terms_exclusions_example', 10, 2 ); function list_terms_exclusions_example( $exclusions, $args ) { // IDs of terms to be excluded $exclude = "42,132"; $exterms = wp_parse_id_list( $exclude ); foreach ( $exterms as $exterm ) { if ( empty( $exclusions ) ) $exclusions = ' AND ( t.term_id <> ' . intval( $exterm ) . ' '; else $exclusions .= ' AND t.term_id <> ' . intval( $exterm ) . ' '; } if ( !empty( $exclusions ) ) $exclusions .= ')'; return $exclusions; } // Example source: http://shailan.com/2598/how-to-exclude-categories-and-tags-from-your-widgets/ ?>
Here's an interesting feature: This filter also hides the terms from your back-end lists. Cool... and creepy.
Changing the Image Sizes Dropdown
If you pick an image to use in your posts, you get to choose a size before adding it to the post content. This handy filter allows us to add custom image sizes (created with the add_image_size()
function beforehand) to the dropdown menu where we select sizes.
Example: Letting Writers Choose Custom Image Sizes
Suppose you already created a custom image with a name of "golden-ratio-thumb" and you need your authors to add images with that size into their posts when necessary. Here's how you add the custom image size to the <select>
menu:
<?php add_filter( 'image_size_names_choose', 'image_size_names_choose_example' ); function image_size_names_choose_example( $sizes ) { return array_merge( $sizes, array( 'golden-ratio-thumb' => __( 'Golden Ratio Thumbnail' ) ) ); } // Example source: http://codex.wordpress.org/Plugin_API/Filter_Reference/image_size_names_choose ?>
It's almost too easy, right?
Changing the "More" String on Excerpts
WordPress cuts off the first 55 words of your posts, removes formatting and calls them "excerpts", summaries of the posts. At the end of the excerpts, there is a [...]
string which is kind of annoying for me. Luckily, the excerpt_more
filter allows us to change it.
Example: Adding a Link to the Post After the Excerpt
Let's say you want to change that text and turn it into a link to the post. Here's how you do it:
<?php add_filter( 'excerpt_more', 'excerpt_more_example' ); function excerpt_more_example( $text ) { global $post; return '... <a class="read-more-link" href="' . get_permalink( $post->ID ) . '">Read more</a>'; } ?>
So now, that annoying bit of text has been put to good use.
Managing Columns in the Posts List
On the Posts page in your admin panel, you can see the list of your posts as a table with additional information like authors, categories, tags of the posts.
The manage_posts_columns
allows us to hide them or add new ones (by using actions and action functions).
Example: Remove the "Author" Column
If you're the only author in your website, you don't need to see the author of each post; so you might as well remove that column to save space. Here's how you do it:
<?php add_filter( 'manage_posts_columns', 'manage_posts_columns_example' ); function manage_posts_columns_example( $columns ) { unset( $columns['author'] ); return $columns; } ?>
There you go! By default, there are seven columns which you can hide:
-
cb
(the checkboxes) title
author
categories
tags
comments
date
To make it work in custom post types, you can use the manage_$post_type_posts_columns
where $post_type
is the ID name of your custom post type.
Editing Users' Contact Methods
Did you know that you can add (or remove) fields in user profiles? Yep, that's what the user_contactmethods
filter is for.
Example: Adding User Fields for Social Media Accounts
This is kind of a popular code snippet because WordPress—still—has profile fields like "Jabber" and "AIM" and people want to get rid of them. In this example, we're going to delete some default "contact methods" and add a few new profile fields:
<?php add_filter( 'user_contactmethods', 'user_contactmethods_example' ); function user_contactmethods_example( $contactmethods ) { unset( $contactmethods['yim'] ); unset( $contactmethods['aim'] ); unset( $contactmethods['jabber'] ); $contactmethods['facebook'] = 'Facebook'; $contactmethods['twitter'] = 'Twitter'; $contactmethods['gplus'] = 'Google+'; $contactmethods['linkedin'] = 'LinkedIn'; $contactmethods['instagram'] = 'Instagram'; return $contactmethods; } ?>
The profile fields look more like 2014 and less like 2002 now, right?
End of Part Three
We went through the second batch of 50 filters 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 filters? Post your comments below; and if you liked the article, don't forget to share it!
Comments