Back

Custom Shortcode for Displaying Posts Loop

This Snippets will help you to create  any post query by WordPress Short code. You can use this trick on your custom post type

function saz_post_loop_shortcode( $atts ) {

	// Parse your shortcode settings with it's defaults
	$atts = shortcode_atts( array(
		'posts_per_page' => '-1'
	), $atts, 'getpost' );

	// Extract shortcode atributes
	extract( $atts );

	// Define output var
	$output = '';

	// Define query
	$query_args = array(
		'post_type'      => 'post', // Change this to the type of post you want to show
		'posts_per_page' => $posts_per_page,
	);

	// Query posts
	$new_query = new WP_Query( $query_args );

	// Add content if we found posts via our query
	if ( $new_query->have_posts() ) {

		// Loop through posts
		while ( $new_query->have_posts() ) {

			// Get te values like title, content, etc
			$new_query->the_post();

			// This is the output for your entry so what you want to do for each post.
			$output .= '
<div>' . get_the_title() . '</div>

';

		}
		// Restore Post data
		wp_reset_postdata();

	}
	// Return your shortcode output
	return $output;
}
add_shortcode( 'getpost', 'saz_post_loop_shortcode' );

Example Shortcode / Usages: [getpost posts_per_page='10']

Get in touch_

Or just write me a letter here_