How to extend a wordpress core widget?

Default, wordpress has many useful widgets, example with The Categories widget. Now look in the class WP_Widget_Categories it located at wp_includes/widgets/class-categories-widget.php

class WP_Widget_Categories extends WP_Widget 
{
    /**
     * Sets up a new Categories widget instance.
     *
     * @since 2.8.0
     * @access public
     */
    public function __construct() 
    {
        $widget_ops = array(
            'classname' => 'widget_categories',
            'description' => __( 'A list or dropdown of categories.' ),
            'customize_selective_refresh' => true,
        );
        parent::__construct( 'categories', __( 'Categories' ), $widget_ops );
    }
    //...
}

We have an option in $widget_ops array, I want to edit the classname widget_categories.

Read More

Another example with Search Widget

public function __construct() 
{
    $widget_ops = array(
        'classname' => 'widget_search',
        'description' => __( 'A search form for your site.' ),
        'customize_selective_refresh' => true,
    );
    parent::__construct( 'search', _x( 'Search', 'Search widget' ), $widget_ops );
}

Sometime we need to edit some string here.

So How can we extend these class? Of course I do not want to edit these core file

Related posts

Leave a Reply

1 comment

  1. If you want to add a custom class to all of your widgets you can do this when you register your sidebar. The before_widget parameter is where classnames are output.

    <?php    
    add_action( 'widgets_init', 'theme_slug_widgets_init' );
        function theme_slug_widgets_init() {
            register_sidebar( array(
                'name' => __( 'Main Sidebar', 'theme-slug' ),
                'id' => 'sidebar-1',
                'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
                'before_widget' => '<li id="%1$s" class="widget %2$s">', // this is where you would add additional classes
                'after_widget'  => '</li>',
                'before_title'  => '<h2 class="widgettitle">',
                'after_title'   => '</h2>',
            ) );
        }
    

    If you want more granular control you can use the dynamic_sidebar_params filter to loop through the widgets in a sidebar an change the before_title paramater for a specific widget.

    add_filter( 'dynamic_sidebar_params', 'my_dynamic_params' );
    
    function my_dynamic_params( $params ) {
    
        foreach ( $params as $key => $param ) {
    
            // check to see if the widget is a category widget
            if ( $param['widget_name'] == 'Categories' ) {
                $params[$key]['before_widget'] = '<li id="' . $param['widget_id'] . '" class="widget my-custom-class">';
            }
        }
    
        return $params;
    }