Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

How to create a shortcode for a WP_Query loop?

I'm doing the basic PHP for Wordpress and I'm having some problems trying to implement a shortcode for a WP_Query Loop.

This is my WP_Query code, which works pretty sweet as a Template Page.

<?php 
                $args = array(
                    'post_type' => 'art',
                    'orderby' => 'title',
                    'order' => 'ASC'
                );
                $the_query = new WP_Query( $args );         
            ?>
            <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 

            <?php get_template_part( 'content', 'art' ); ?>

            <?php endwhile; endif; ?>

But I will like to use it not only inside a template page, but anywhere I want. Therefore I need to create a shortcode. Example:

function foobar_func( $atts ){
    return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

My question would be: How can i put the loop inside my shortcode?

1 Answer

Hi sorry for the delay in getting an answer to you,

have you managed to get to the bottom of this one?

Craig :)