Random Posts widget with caching

<?php
/**
* Favorite Widget
*
* @package Core_Functionality
* @since 1.0.0
* @link https://github.com/billerickson/Core-Functionality
* @author Bill Erickson <[email protected]>
* @copyright Copyright (c) 2011, Bill Erickson
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
*/
class BE_Favorite_Widget extends WP_Widget {
/**
* Constructor
*
* @return void
**/
function BE_Favorite_Widget() {
$widget_ops = array( 'classname' => 'widget_favorite', 'description' => 'Displays 8 random posts marked favorite' );
$this->WP_Widget( 'favorite-widget', 'Favorite Images', $widget_ops );
}
/**
* Outputs the HTML for this widget.
*
* @param array An array of standard parameters for widgets in this theme
* @param array An array of settings for this widget instance
* @return void Echoes it's output
**/
function widget( $args, $instance ) {
extract( $args, EXTR_SKIP );
echo $before_widget;
$popular = wp_cache_get( 'be_popular_posts' );
if( false === $popular ) {
$popular = $this->load_popular_posts();
$expire = 60 * 60 * 24; // Cache data for one day (86400 seconds)
wp_cache_set( 'be_popular_posts', $popular, 'be_cache', $expire );
}
echo $popular;
echo $after_widget;
}
/**
* Load Popular Posts
* @ return string, popular post output
*/
function load_popular_posts() {
$loop_args = array(
'posts_per_page' => 8,
'orderby' => 'rand',
'no_found_rows' => true,
'update_post_term_cache' => false,
'meta_query' => array(
array(
'key' => 'be_favorite_image',
'value' => 'on',
)
)
);
$loop = new WP_Query( $loop_args );
$output = '';
if( $loop->have_posts() ):
$output .= '<p>';
while( $loop->have_posts() ): $loop->the_post(); global $post;
$output .= '<a href="' . get_permalink( $post->ID ) . '">' . get_the_post_thumbnail( $post->ID, 'be_favorite' ) . '</a> ';
endwhile;
$output .= '</p>';
endif;
wp_reset_postdata();
return $output;
}
}
function be_register_favorite_widget() {
register_widget('BE_Favorite_Widget');
}
add_action( 'widgets_init', 'be_register_favorite_widget' );
view raw widget-favorite.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk