Customize default recent posts widget in WordPress

Photo of author
Written By geekerhub

Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis. 

There come a recent posts widget in WordPress. To meet the UI of the active theme, some times we need to re-structure the Widget.

We can manage to do this with the plugin but for the small stuff, it is not advisable to use a plugin to load other unnecessary code.

I suggest to re-initiate the widgets to meet the requirement and below is the code snippet for the same.

Code snippet unregisters the default Recent Widget and registers a new Widget with a different structure. Keep below code snippet in your theme’s functions.php

/**
 * Extend Recent Posts Widget 
 *
 * Adds different formatting to the default WordPress Recent Posts Widget
 */
Class GEEKER_Recent_Posts_Widget extends WP_Widget_Recent_Posts {

    function widget($args, $instance) {
      
        extract( $args );
        
        $title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Posts') : $instance['title'], $instance, $this->id_base);
                
        if( empty( $instance['number'] ) || ! $number = absint( $instance['number'] ) )
            $number = 10;
                    
        $r = new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true ) ) );
        if( $r->have_posts() ) :
            
            echo $before_widget;
            if( $title ) echo $before_title . $title . $after_title; ?>
            <ul>
                <?php while( $r->have_posts() ) : $r->the_post(); ?>                
                <li>
                    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
                    <?php 
                        if( !empty( $instance['show_date'] ) )
                            the_time( 'F j, Y .'); 
                    ?>
                    <?php echo do_shortcode('[wpbb post:terms_list taxonomy="category" separator=", "]'); ?>
                </li>
                <?php endwhile; ?>
            </ul>
             
            <?php
            echo $after_widget;
        wp_reset_postdata();
        endif;
    }
}

function geeker_recent_widget_registration() {
    unregister_widget('WP_Widget_Recent_Posts');
    register_widget('GEEKER_Recent_Posts_Widget');
}

add_action('widgets_init', 'geeker_recent_widget_registration');

Leave a Comment