Snippets: Simple Custom Shortcode for Displaying Posts

// Add a new custom grid shortcode module
// Usage [myprefix_custom_grid posts_per_page="4" term="4"]
// You can also go to Visual Composer > Shortcode Mapper to add your custom module
function myprefix_custom_grid_shortcode( $atts ) {

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

	// 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 by term if defined
	if ( $term ) {

		$query_args['tax_query'] = array(
			array(
				'taxonomy' => 'category',
				'field'    => 'ID',
				'terms'    => $term,
			),
		);

	}

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

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

		// Open div wrapper around loop
		$output .= '<div>';

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

			// Sets up post data so you can use functions like get_the_title(), get_permalink(), etc
			$custom_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>';

		}

		// Close div wrapper around loop
		$output .= '</div>';

		// Restore data
		wp_reset_postdata();

	}

	// Return your shortcode output
	return $output;

}
add_shortcode( 'myprefix_custom_grid', 'myprefix_custom_grid_shortcode' );

Snippet Type: PHP

Posted Under: Other

All PHP snippets should be added via a child theme's functions.php file.