[wp-hackers] Making use of The Loop in a shortcode function

Lox lox.dev at knc.nc
Tue Jun 22 08:02:00 UTC 2010


I am using a Loop in a Wordpress shortcode function. Because it is
really nice ;) and because it allows me to make use of templates for
the shortcode output.

But because the content made by the shortcode function must be
returned and not printed with echo, I have to use output buffering:

public function shortcode_featured ($atts, $content, $code) {
    extract( shortcode_atts( array( 'cat' => 0, 'template' => '') , $atts ) );

    global $wp_query, $post;
    if(!preg_match('/^[a-z0-9\-_]+$/is',$template)) $template='';

    if(!$template) $template = 'Featured';
    $template .= '.php';

    // backup main loop
    $temp_query = clone $wp_query;

    // setup new loop
    $wp_query = new WP_Query('post_type=featured_pages&orderby=rand');

    // look for $template file in current theme directory
    if (file_exists(TEMPLATEPATH.'/'.$template) ) {
	    include (TEMPLATEPATH.'/'.$template);
    // fallback to default template
    else {
	    include( GKNC_PATH . '/Templates/Featured.php' );

    // restore main loop
    $wp_query = clone $temp_query;

    return ob_get_clean();

Isn't their a better way to achieve it ? I find it really ugly....

Best regards.

lox.dev at knc.nc

More information about the wp-hackers mailing list