0

What is the best practice methodology for referencing the main loop from within the context of a secondary loop within a partial called via get_template_part()?

For example, say my homepage contains a secondary loop to list two posts of type article:

<?php
$articles = new WP_Query( array(
    'post_type' => 'article',
    'posts_per_page' => 2
) );
if ( $posts->have_posts() ) : ?>
    <ul>
        <?php
            while ( $articles->have_posts() ) : $articles->the_post();
                get_template_part( 'templates/listing', 'article');
            endwhile;
        ?>
    </ul>
<?php
    endif;
?>

And in /templates/listing-article.php, I have:

<?php if (!is_front_page()) : ?>
    <div><?php the_content(); ?></div>
<?php endif; ?>

Here, the_content() lists the content of the article as expected/intended. is_front_page() returns false as expected, but not as intended - my intention is to show the content if on any page except the homepage.

My question is thus: how does one make conditional template tags like is_front_page() return true/false based on the post in the main loop, as opposed to my secondary loop.

You could set a global variable in your homepage template that you then reference in your partial, but I'm asking if there's a standard, better solution.

  • 1
    The home page and front page are not always the same. is_home() returns true on the posts page according to your reading settings and is_front_page() always returns true for the front page regardless of your reading settings – Brad Dalton Aug 3 '14 at 10:40
  • 1
    Note that your line 6 should read if ( $articles->have_posts() ) : (not $posts). But this is most likely not your actual code... – tfrommen Aug 3 '14 at 10:46
1

You can ask the main query directly (which is, in fact, exactly what the is_front_page function is doing).

<?php global $wp_query; ?>
<?php if ( $wp_query->is_front_page() ) : ?>
    <div><?php the_content(); ?></div>
<?php endif; ?>

If you altered the main query, however, refer to the backup.

<?php global $wp_the_query; ?>
<?php if ( $wp_the_query->is_front_page() ) : ?>
    <div><?php the_content(); ?></div>
<?php endif; ?>

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.