Skip to content

Instantly share code, notes, and snippets.

@bueltge
Created January 4, 2012 09:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bueltge/1559249 to your computer and use it in GitHub Desktop.
Save bueltge/1559249 to your computer and use it in GitHub Desktop.
Custom Query Shortcode: Run a Loop inside any Post/Page
<?php
/**
* Plugin Name: Custom Query Shortcode
* Plugin URI:
* Description: Run a Loop inside any Post/Page via Shortcode <code>[loop]</code>
* Version: 0.0.1
* License: GPLv3
* Author: Frank B&uuml;ltge
* Author URI: http://bueltge.de/
*/
// This file is not called from WordPress. We don't like that.
! defined( 'ABSPATH' ) and exit;
/**
* EXAMPLE USAGES:
* [loop]
* [loop query="posts_per_page=3"]
* [loop the_query="showposts=15&post_type=post&post_parent=453"]
*
* @param $before string Markup,content Before content of loop output
* @param $after string Markup,content After content of loop output
* @param http://codex.wordpress.org/Class_Reference/WP_Query
* @see http://codex.wordpress.org/Class_Reference/WP_Query
*/
function fb_custom_query_shortcode( $atts ) {
// Defaults
extract( shortcode_atts( array(
'the_query' => '',
'before' => '<ul>',
'after' => '</ul>'
), $atts ) );
// de-funkify query
$the_query = preg_replace( '~&#x0*([0-9a-f]+);~ei', 'chr( hexdec("\\1") )', $the_query );
$the_query = preg_replace( '~&#0*([0-9]+);~e', 'chr(\\1)', $the_query );
// query is made
query_posts( $the_query );
// Reset and setup variables
$output = '';
$temp_title = '';
$temp_link = '';
// the loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
$temp_title = get_the_title( $post->ID );
$temp_link = get_permalink( $post->ID );
// output all findings - CUSTOMIZE TO YOUR LIKING
$output .= '<li><a href="' . $temp_link . '">' . $temp_title . '</a></li>';
endwhile; else:
$output .= __( 'nothing found.' );
endif;
wp_reset_query();
return $before . $output . $after;
}
add_shortcode( 'loop', 'fb_custom_query_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment