Adding Custom Query Loop as Shortcode Post Types Taxonomies and more

Sometimes some themes and some builders makes the building custom query loops harder. For that reason I wrote this simple code and added t other themes functions.php

This is a very simple example it is possible make this much much more advance. Check the WP docs examples -> WP_Query | Class | WordPress Developer Resources

add this code to the theme functions.php

and usage shortcode -> [get_last_posts]

/*
*
*	Registering Shortcode for Post Types
*   
*   Usage:   [get_last_posts]
*	
*	Custom Shortcode with Custom Query Loop for Custom post Types and Taxonomies and Stuff
*
*/
function get_the_last_posts( ) {
     $qquery = new WP_Query(array(
          'post_type' => 'post',
          'posts_per_page' => 5
     ));
     while ($qquery->have_posts()){
               $qquery->the_post();
          ?>

          <h2>
               <?php echo get_the_title(); ?>	
          </h2>
          <p>
               <?php echo get_the_content(); ?>	
          </p>
          <p>
               <?php  echo get_post_meta( get_the_ID(), 'name' , true ); ?>
          </p>

          <?php
     }
          wp_reset_postdata();
}
add_shortcode( 'get_last_posts', 'get_the_last_posts');

this example only shows latest 5 post and title and content and example customfield value.

 

recommended plugin Dynamic Shortcode Widget for Elementor – WordPress plugin | WordPress.org

another similar useful plugin Custom Content Shortcode – WordPress plugin | WordPress.org

Leave the first comment