WordPress widget wp_query params from shortcode variable

I have a widget that shows related posts in the sidebar.
I would like to manipulate the widget’s wp_query parameters using a shortcode in the page.

The reason I would like to do so is that it’s a multipages post (with page breaks) and each page is related to a different category.
I would like the widget to show recommended posts according to the specific page.

I am not sure how to make to widget evaluate the shortcode ($a["cat"]) before running the wp_query.

Shortcode function:

    //[bartag cat="computers"]
function bartag_func( $atts ) {
        $a = shortcode_atts( array('cat' => ''), $atts );

        return $a['cat'];
add_shortcode( 'bartag', 'bartag_func' );

The widget function:

class related_articles_Widget extends WP_Widget {

     * Register widget with WordPress.
    function __construct() {
            'related_articles_Widget', // Base ID
            esc_html__( 'related_articles_Widget', 'text_domain' ), // Name
            array( 'description' => esc_html__( '', 'text_domain' ), ) // Args

    public function widget( $args, $instance ) {
        echo $args['before_widget'];

        $args = array( 'post_type' => 'post', 
                'posts_per_page' => 3,
                'category_name' => $a['cat']

            $loop = new WP_Query( $args );

            while ( $loop->have_posts() ) : $loop->the_post(); 

            get_template_part( 'template-parts/content', 'small-article-template');



function register_related_articles_Widget() {
    register_widget( 'related_articles_Widget' );
add_action( 'widgets_init', 'register_related_articles_Widget' );

Read more here: WordPress widget wp_query params from shortcode variable

Leave a Reply

Your email address will not be published. Required fields are marked *