Add caching to your plugin


Sooner or later, we all write something that could make use of some caching.  I’ve seen several plugins store cache data using the options API — though this will work, it’s probably not the right place to do this.  Instead, you can easily use the WordPress transient API.  Unlike the options API, the Transients API gives you the option of an expiration.  Perfect for caching a query that needs updating, but doesn’t need run every time your code runs.  Here’s how it works:

function hwp_cached_query() {

	if ( false === ( $hwp_query_results = get_transient( 'hwp_query_results' ) ) ) {
		$hwp_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
		set_transient( 'hwp_query_results', $hwp_query_results, 60*60*24 );
	}

	while ( $hwp_query_results->have_posts() ) : $hwp_query_results->the_post();
		echo '
<ul>
	<li>'; the_title(); echo '</li>
</ul>
';
	endwhile;

	// Reset Post Data
	wp_reset_postdata();

Quick breakdown:

	if ( false === ( $hwp_query_results = get_transient( 'hwp_query_results' ) ) ) {

Here we check to see if the transient entry exists.

		$hwp_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
		set_transient( 'hwp_query_results', $hwp_query_results, 60*60*24 );

If our cached data doesn’t exist, we’ll run our query and cache it. In this case, we’re calling our cached entry ‘hwp_query_results’, using the $hwp_query_results variable, and setting the expiration for 24 hours.


Change the “Enter Title Here” text in WordPress


Though custom post types have a lot of label configuration options, the one glaring omission was the in-field “Enter Title Here” text that appears in the title field. Since the “title” area of a custom post type may not necessarily used for a “Title”, changing this will reduce confusion and make better sense from a UX point-of-view. Well, guess what? There’s a filter for that!

function hwp_enter_title_here( $title ){
	$screen = get_current_screen();

	if ( 'custom_post_type' == $screen->post_type ) {
		$title = 'Custom Post Type Title Text';
	}

	return $title;
}

add_filter( 'enter_title_here', 'hwp_enter_title_here' );

Quick breakdown:

	$screen = get_current_screen();

This gets our current admin screen attributes — we’ll use this to make sure we’re viewing our custom post type.

	if ( 'custom_post_type' == $screen->post_type ) {
		$title = 'Custom Post Type Title Text';
	}

Here we check for our post type (replace “custom_post_type” with the name of your post type) and define the title text.

	return $title;

Finally, our function returns the title field text to the filter.

add_filter( 'enter_title_here', 'hwp_enter_title_here' );

All we need to do is add our new function to the ‘enter_title_here’ filter.