Skip to content

Instantly share code, notes, and snippets.

@rumur
Created November 10, 2016 12:57
Show Gist options
  • Save rumur/5a47aabc7273ae47144f874e6c55f855 to your computer and use it in GitHub Desktop.
Save rumur/5a47aabc7273ae47144f874e6c55f855 to your computer and use it in GitHub Desktop.
WP Widget Inheritance
<?php
/**
* Created by PhpStorm.
* User: rumur
* Date: 11/10/16
* Time: 13:13
*/
class BS_Recent_Category_Posts extends WP_Widget_Recent_Posts {
protected $textdomain = 'bs';
protected $class_prefix = 'bs_';
protected $cat = 0;
function __construct() {
$this->textdomain = defined( 'BS_TEXT_DOMAIN' ) ? BS_TEXT_DOMAIN : $this->textdomain;
$widget_ops = array(
'classname' => $this->prep_class( 'widget_recent_category_entries' ),
'description' => __( 'The most recent posts from specific category on your site.', $this->textdomain ),
'customize_selective_refresh' => true,
);
WP_Widget::__construct( 'bs-recent-posts', __( 'Recent Category Posts', $this->textdomain ), $widget_ops );
}
protected function prep_class( $class ) {
return $this->class_prefix . $class;
}
public function extends_widget_posts_args( $args ) {
$args['cat'] = $this->cat;
return $args;
}
public function update( $new_instance, $old_instance ) {
$instance = parent::update( $new_instance, $old_instance );
$instance['cat'] = (int) $new_instance['cat'];
return $instance;
}
public function form( $instance ) {
$cat = isset( $instance['cat'] ) ? $instance['cat'] : 0;
parent::form( $instance );
?>
<p>
<label>
<?php _e( 'Category', $this->textdomain ); ?>:
<?php wp_dropdown_categories( array(
'name' => $this->get_field_name( 'cat' ),
'selected' => $cat
) ); ?>
</label>
</p>
<?php
}
public function widget( $args, $instance ) {
$this->cat = $instance['cat'];
add_filter( 'widget_posts_args', array( $this, 'extends_widget_posts_args' ) );
unset( $instance['cat'] );
parent::widget( $args, $instance );
remove_filter( 'widget_posts_args', array( $this, 'extends_widget_posts_args' ) );
}
}
add_action( 'widgets_init', function() {
register_widget( 'BS_Recent_Category_Posts' );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment