Hi Everyone,

Today I will be sharing my experience on building shortcode from registered widgets. I had developed this feature on Styled Store Pro making all the custom widgets available as shortcode. A shortcode can be very useful on using the dynamic content on post/pages content and text widgets.

I hope you guys know how to build custom widgets and shortcode. If not please go through these link:
Widgets API
Shortcode API

Here our logic is to developing shortcode calling the_widgets() template tags on our shortcode callback function. the_widgets() accepts the instance which we will be sending as shortcode parameter. So let’s use default WordPress recent posts widgets on the shortcode

/**
* @return convert widgets on to shortcode
* @author Sushil Adhikari
*/
add_shortcode( 'theme_slug_recent_post', 'theme_slug_recent_posts' );
function theme_slug_recent_posts( $atts ) {
    $atts = shortcode_atts( array( 
       'title' => esc_html__( 'Recent post', 'theme-slug' ),
       'number' => 5,
       'show_date' => false
    ), $atts );
    $instance = array(); 
    $instance[ 'title'] = $atts[ 'title' ]; 
    $instance[ 'number'] = isset( $atts[ 'number' ] ) ? absint( $atts[ 'number' ] ) : 5;
    $instance[ 'show_date'] = isset( $atts[ 'show_date' ] ) ? ( bool ) $atts[ 'show_date' ] : false; 
    ob_start(); 
    the_widget( 'WP_Widget_Recent_Posts', $instance ); 
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

You need to add this function on the functions.php file.

After this you can add the following shortcode on to page, post or text widgets.

[theme_slug_recent_post title="Widgets to Shortcode" number="1" show_date="true"]

Thank you for going through this tutorial, your suggestion and feedback will be highly appreciated.

Thanks

Advertisements