igmoweb
11/19/2015 - 11:25 AM

Custom query shortcode

Custom query shortcode

<?php

add_shortcode( 'areas', 'custom_query_shortcode' );
function custom_query_shortcode( $atts ) {
	// EXAMPLE USAGE:
	// [areas show_posts="100" post_type="page" post_parent="246"]
	// Defaults
	$defaults = array(
		"show_posts" => 100,
		"post_type" => 'page',
		"post_parent" => false
	);
	$atts = shortcode_atts( $defaults, $atts );
	extract( $atts );

	// El post type está bien?
	if ( in_array( $post_type, array( 'attachment', 'revision', 'nav_menu_item' ) ) ) {
		return 'nothing found';
	}

	// El post parent existe?
	if ( ! get_post( $post_parent ) )
		return "Nothing found";

	$query_args = array(
			'ignore_sticky_posts' => true,
			'post_parent' => $post_parent,
			'post_type' => $post_type,
			'posts_per_page' => $show_posts
	);
	$the_query = new WP_Query( $query_args );
	// Reset and setup variables
	$output = '';

	// the loop
	if ($the_query->have_posts()) :
		while ($the_query->have_posts()) : $the_query->the_post();
			$output .= "<li><a href='" . esc_url( get_permalink() ) . "'></a>" . get_the_title() . "</li>";
		endwhile;
		wp_reset_query();
	else:
		$output .= "nothing found.";
	endif;
	return $output;
}