• I am looking to build both a shortcode and a widget with essentially the same functionality, however, it seems short sighted to duplicate the code so I am curious what suggestions people might have for integrating the two.

    I have read a couple of articles about creating a shortcode that allows you to embed a widget in a page/post.

    My initial thought was to write a shortcode and then just use the widget interface to configure the attributes. Just not sure how to then render the shortcode in place of the widget… or if that will even work.

    Any input and ideas are appreciated! Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • You could address this in at least two ways.
    1. Create your widget, and then create a shortcode which essentially wraps the widget using https://codex.www.ads-software.com/Function_Reference/the_widget . the_widget lets you pass it instance args, so you would then simply map the shortcode_atts to the instance args.

    2. Create a view layer function which simply takes the expected args and handles the visual display. So that function would simply handle and return the html output for the widget and shortcode. Then both the shortcode and the widget could call that view function. So for example in your widget class, in the widget function, between echo $args['before_widget']; and echo $args['after_widget']; you would just echo out the result of that html view layer function.

    I hope that helps!

    IMO, the hardest part of this is the abstraction between the two, and how to serve-up the template output.

    bbPress has largely solved this problem:

    https://bbpress.trac.www.ads-software.com/browser/trunk/src/includes/common/shortcodes.php

    As you can see, it uses it’s own bbp_get_template_part() functionality, which is basically get_template_part() with an additional check for shortcode-name.php style template parts inside of bbPress’s plugin directory to use as fallbacks if neither the child nor parent theme have built-in support already (which they largely never will.)

    Please use bbPress as an example for this; it’s historically been a great example of doing all the best things WordPress has to offer, but cranked to 11.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Shared Functionality Between Widget and Shortcode’ is closed to new replies.