-1

I would like to create a WordPress plugin/widget that I can add to my post either through the Visual Composer area (widget should be selectable) or simply as a shortcode.

The functionality of this widget is that it should allow me to take the settings of that post as an argument in the main function so that I can change the output of the widget based on what is selected for the post.

For example, I have categories for all my posts and if I have a certain category selected, I want to change the output of the widget based on that.

Does anyone know of a good boilerplate to get me started with this?

Thanks

Justin
  • 623
  • 1
  • 10
  • 24

1 Answers1

1

You can create your own widget using the Widget API or the Shortcode API for shortcodes.

Since you want to change the content shown in your, for instance, widget, based on the current post, in the widget() method (which is the method that prints your widget's content in the frontend) you can add your conditionals or whatever you want to print there.

The $post is available in your widget, so you can use functions like get_post_meta() to retrieve the post's settings if you use custom fields, or any other function like get_the_ID() or has_category().

For example:

/**
 * Outputs the content of the widget
 *
 * @param array $args
 * @param array $instance
 */
public function widget( $args, $instance ) {
    if ( has_category( 'books' ) ) {
        echo 'Hey!, I have the Books category!';
    } else {
        echo "Hey... I don't.";
    }
}
Mithc
  • 851
  • 8
  • 23
  • Thank you so much for your reply. It helped me get to the answer I needed. Within the shortcode function, I was able to use `get_post()` which returned me all my post data as well as `wp_get_object_terms( $id, 'portfolio_categories')` which helped me get the list of categories for my post. Thanks! – Justin Aug 27 '17 at 22:14