2

Wordpress 4.x

Why does the loop.php only show the current post in the sidebar when I view a post in single.php?

I have:

  1. Post One
  2. Post Two
  3. Post Three

If I view "Post One" (single.php), the sidebar only shows "Post One", if I view the page I have set as the "Blog" page (index.php) in Wordpress admin, I see all the posts in the sidebar.

My goal is to have all posts show in the single.php sidebar. Would be nice to remove the current posts as well! But mostly want to understand the relationship/structure here.

Working with a custom theme based on the HTML5 Blank theme, no major custom functionality.

First Wordpress site and this feels like a fundamental structure aspect.

sidebar.php

<aside class="sidebar column" role="complementary">

    <?php get_template_part('searchform'); ?>

    <?php get_template_part('loop'); ?>
    <?php get_template_part('pagination'); ?>

    <div class="sidebar-widget">
        <?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('widget-area-1')) ?>
    </div>

    <div class="sidebar-widget">
        <?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('widget-area-2')) ?>
    </div>

</aside>

loop.php

<?php if (have_posts()): while (have_posts()) : the_post(); ?>

    <article class="loop-template" id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

        <!-- article content here -->

    </article>

<?php endwhile; ?>

<?php else: ?>

    <article>

        <!-- else content here -->

    </article>

<?php endif; ?>

Then in single.php I am calling <?php get_sidebar(); ?> outside of any loop or conditional.

  • better to post some code , it's confusing ..you might not be running inside the loop – Latheesh V M Villa Dec 9 '18 at 16:20
  • Added what I believe is the relevant code to my question. – Prestosaurus Dec 9 '18 at 17:34
  • 1
    You have not initiated the WP query for sidebar in loop.php – Latheesh V M Villa Dec 9 '18 at 17:41
0

Initiating new WP_Query($post) shows all posts. Credit to @Latheesh V M Villa

Add:

$loop_query = new WP_Query($post)

Then change loop values like:

have_posts()

to:

$loop_query->have_posts()

loop.php

<?php $loop_query = new WP_Query($post); if ($loop_query->have_posts()): while ($loop_query->have_posts()) : $loop_query->the_post(); ?>
    <article class="loop-template" id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <!-- article content here -->
    </article>
<?php endwhile; ?>
<?php else: ?>
    <article>
        <!-- else content here -->
    </article>
<?php endif; ?>

It appears you can leave everything inside the loop alone such as the_ID() and the_title().

Great article at smashingmagazine here

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.