Skip to content

Instantly share code, notes, and snippets.

@igmoweb
Last active November 19, 2015 13:54
Show Gist options
  • Save igmoweb/d2451b4d21bd3e01b2e6 to your computer and use it in GitHub Desktop.
Save igmoweb/d2451b4d21bd3e01b2e6 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment