Best practices regarding the creation of custom widgets?

Literally, you can place the widget code anywhere inside your theme files (except template files) and include them from functions.php file.

functions.php is the only file that WordPress includes when you theme
is active

There is no best practice where you put them, but that doesn’t mean you should mess things up. It is best to keep each of your widget code inside a separate file.


To keep things organized, you can put each of your widget files inside any of the following folder of your theme:

  • /includes/
  • /widgets/
  • /includes/widgets/

Naming widget file:

You can only register a custom widget by extending WP_Widget class. That indicates you need to write a class for each widget. Considering this, your widget files should be named with a class prefix. Like: class-widget-one.php PHP file prefixed with a class indicates this file contain only one class.


Registering widgets:

It’s better to register all of you widgets from functions.php. That’s makes it easy understand how many custom widget your theme providers, and where they are located.

function wpse366458_register_widgets() {
    include( dirname( __FILE__ ) . '/widgets/class-widget-one.php' );
    register_widget( 'Theme_Widget_One' );

    include( dirname( __FILE__ ) . '/widgets/class-widget-two.php' );
    register_widget( 'Theme_Widget_Two' );
}
add_action( 'widgets_init', 'wpdocs_register_widgets' );

Reusing codes over multiple widgets:

Now it completely depends on your needs and taste. You can –

  • use Trait class and methods will be available inside your current widget class. ie: get_page_choices().
  • use class with static methods. ie: Prefix_Widget_Helper::get_page_choices()
  • use functions. ie: prefix_get_page_choices(), prefix_sanitize_something()