WordPress-Plugin-Boilerplate icon indicating copy to clipboard operation
WordPress-Plugin-Boilerplate copied to clipboard

Creating a Widget in a proper way

Open devcon7 opened this issue 9 years ago • 3 comments

I found a similar question, but I wasn't sure about if we are having the same questions.

Basically, I want to find out the best practice way of creating a widget to display the /public/partials/plugin-name-public-display.php

I got the shortcode working, but also want to use widgets.

Please advise.

devcon7 avatar Jun 25 '15 05:06 devcon7

Check out https://wordpress.org/plugins/beautiful-taxonomy-filters/

It creates some widgets for its functionality that might be good examples for you.

DevinVinson avatar Jun 25 '15 13:06 DevinVinson

Hi @devcon7

I'm the author of BTF as linked above :) I am in no way a hardcore developer but I'll explain how I solved the widget scenario. It's pretty simple.

I decided that I wanted all widgets in a separate folder in the plugin root. There were two reasons for this:

  1. A widget exists both in admin and public. There's code to show the widget in appearance/widgets and there's obviously the code to show the widgets content on your front-end. This arguments that the widget should be placed in the includes folder but:
  2. the includes folder already contains many core classes which is critical for the plugin to function and while the widgets are a big part of my plugin they're not critical. There's also the fact that I knew at the time that I was going to create two widgets with the possibility of more in the future and keeping them separate made for a cleaner code in my opinion.

So here's how I did it. I put each separate widget in it's own file inside plugin/widgets, for example beautiful-taxonomy-filters-widget.php and wrapped all code in the usual class class Beautiful_Taxonomy_Filters_Widget extends WP_Widget {. Then I included each widget file in load_dependencies(). And finally I register the widgets by an admin action $this->loader->add_action( 'widgets_init', $plugin_admin, 'register_widgets' );

/**
 * Create our custom filter widget
 *
 * @since    1.0.0
 */
public function register_widgets() {

    register_widget( 'Beautiful_Taxonomy_Filters_Widget' );
    register_widget( 'Beautiful_Taxonomy_Filters_Info_Widget' );

}

There you have it :) I'm not saying it's the way to go but it's worked just fine for me!

jonathan-dejong avatar Mar 20 '16 11:03 jonathan-dejong

@jonathan-dejong Aren't widgets more of a public thing?

re1 avatar Aug 21 '18 14:08 re1