Created
April 18, 2020 01:42
-
-
Save ansballard/7ca1fae69ec1a4370c70256f021eb068 to your computer and use it in GitHub Desktop.
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
<?php | |
/* | |
Plugin Name: DWF Popular Posts Widget | |
Description: Displays posts in last X days, sorted by most comments (proxy for popularity) | |
*/ | |
/** Add our function to the widgets_init hook. **/ | |
add_action( 'widgets_init', 'dwf_popular_load_widgets' ); | |
function dwf_popular_load_widgets() { | |
register_widget('DWF_Popular_Widget'); | |
} | |
/** Define the Widget as an extension of WP_Widget **/ | |
class DWF_Popular_Widget extends WP_Widget { | |
public function __construct() { | |
/* Widget settings. */ | |
$widget_ops = array('classname' => 'widget_popular', 'description' => 'Displays most popular posts by comment count (no title trimming)'); | |
/* Widget control settings. */ | |
$control_ops = array('id_base' => 'dwf-popular-widget'); | |
/* Create the widget. */ | |
parent::__construct( 'dwf-popular-widget', 'DWF Popular Posts', $widget_ops, $control_ops); | |
} | |
function widget($args, $instance) { | |
extract($args); | |
$loop_args = array( | |
'orderby' => 'meta_value_num', | |
'order' => 'desc', | |
'meta_key' => 'views' | |
); | |
$loop = new WP_Query( $loop_args ); | |
if($loop->have_posts()) { | |
echo $before_widget; | |
if(!empty($instance['title'])) { | |
echo $before_title . $instance['title'] . $after_title; | |
} | |
?> <div class="mu-grid-row"> <?php | |
while($loop->have_posts()) { | |
$loop->the_post(); | |
get_template_part('template-parts/content-style-grid'); | |
} | |
?> </div> <?php | |
echo $after_widget; | |
} | |
} | |
function update($new_instance, $old_instance) { | |
$instance = $old_instance; | |
/* Strip tags (if needed) and update the widget settings. */ | |
$instance['title'] = esc_attr($new_instance['title']); | |
return $instance; | |
} | |
function form($instance) { | |
/* Set up some default widget settings. */ | |
$defaults = array('title' => ''); | |
$instance = wp_parse_args((array)$instance, $defaults); ?> | |
<p> | |
<label for="<?php echo $this->get_field_id('title'); ?>">Title:</label> | |
<input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" /> | |
</p> | |
<?php | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment