<?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' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters