0

I have a custom post type work-gallery and a custom taxonomy use which serves to categorize the posts.

I am trying to develop a shortcode which enables me to output the work-gallery posts that belong to a particular use.I suppose it would be the equivalent of a category archive query except that I want to be able to use it on different pages.

The code looks like this:

function wg_album($wguse){ 
extract(shortcode_atts(
    array('use' => 'work'), $wguse)); 
    $args = array(
        'post_type'   => 'work-gallery',
        'tax_query' => array(
                array(
                    'taxonomy' => 'use',
                    'field' => 'slug',
                    'terms' => $use
                )
            )
        );
$work_galleries = new WP_Query($args);
ob_start(); ?>
    <ul class="work-pages">
<?php foreach ($work_galleries as $work_gallery) { ?>       
        <li>
            <a href="<?php echo get_page_link( $work_gallery -> ID ); //the permalink?>">

                <?php echo get_the_post_thumbnail($work_gallery -> ID)//the featured image?>
                <h3><?php echo $work_gallery -> post_title ; ?></h3>

            <p> <?php echo $work_gallery -> post_excerpt ; ?></p>
            </a>
        </li>

<?php } ?>
    </ul>
<?php return ob_get_clean(); 
} ?>

What I get, instead of output of the permalink, title, featured image and excerpt - as in the code - is the permalink of the host page, iterated 40 times!

What am I doing wrong ? The problem, I think is in the query.

1

That is a very broken Loop. The results of a new WP_Query is not a simple array that you can foreach over. It is far more complicated than that. Try var_dump($work_galleries);.

Fortunately, WP_Query provides methods to make looping easy.

$work_galleries = new WP_Query($args);
if ($work_galleries->have_posts()) {
  while ($work_galleries->have_posts()) { // this replaces foreach
    $work_galleries->the_post(); // this sets up the post data so functions like the_title() work
    // now your code
  }
}
  • Thanks for a speedy reply that works !! get_posts() uses a foreach loop, doesn't it ? What is the difference from WP_Query and which is better ? Before I moved the galleries to a custom post type I used get_pages(), that's why I used a foreach... – Nick Nov 26 '13 at 17:00
  • get_posts uses WP_Query internally and just returns the actual array of results. I rarely use anything but WP_Query but whether that is "better" is a judgement call. – s_ha_dum Nov 26 '13 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.