Randy Hall
Randy Hall

Reputation: 8127

Get WordPress title without the_post

I need to loop through a set of posts before the main content in a page template. That's easy:

$getCoverArticles = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'slug',
            'terms'    => 'cover',
        ),
    )
);

$queryCoverArticles = new WP_Query( $getCoverArticles );

if($queryCoverArticles->have_posts() ) {
  while($queryCoverArticles->have_posts() ) {
    $queryCoverArticles->the_post();
    ?>
        <a><?php the_title(); ?></a>
    <?php
  }
}

Problem is, the method sets the global post object, so trying to get the_content() after this loop gives the content for the last post in the loop...

Seems a bit extreme to juggle around the global post object just for a title property. Is there a way to easily get at the title without assigning it as the global object?

Upvotes: 0

Views: 161

Answers (3)

Dhruv
Dhruv

Reputation: 612

Please try with following code, I hope this will works for you.

<?php

if ($queryCoverArticles->have_posts() ) :
    while ( $queryCoverArticles->have_posts() ) : $queryCoverArticles->the_post();
        ?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
    endwhile;
endif;
wp_reset_postdata();
?>

Upvotes: 0

Azer
Azer

Reputation: 1288

Add wp_reset_postdata(); just after you're done with the extra query and the query should be restored so that the global $post refers to the current post in the main query.

Upvotes: 1

cabrerahector
cabrerahector

Reputation: 3948

From the documentation:

Note: If you use the_post() with your query, you need to run wp_reset_postdata() afterwards to have Template Tags use the main query's current post again.

So:

if($queryCoverArticles->have_posts() ) {
  while($queryCoverArticles->have_posts() ) {
    $queryCoverArticles->the_post();
    ?>
        <a><?php the_title(); ?></a>
    <?php
  }
}

// Restore original post data
wp_reset_postdata();

... should fix the issue.

Upvotes: 2

Related Questions