WordPress.org

Ready to get started?Download WordPress

Forums

custom loop in order by category, syncs with next and previous post navigation (1 post)

  1. vtmnD
    Member
    Posted 1 year ago #

    Thanks for any help that can be provided. My site is being locally developed, I have no link to share.

    I am trying to sort my content in order by category, all posts are assigned a single category, and I want the home page excerpts to go in order cat1, cat2, cat3, cat4. I accomplished this in a sense, but know that it no longer order posts the same order as when clicking the previous and next_post_link buttons on a single post page.

    I know I will have to adjust how I create my custom query if I want it to work universally. Below is what I have now. I think I need to modify the main loop query so that all posts are always called in the same order.

    I also know I can probably do this more efficiently in an array and a for loop but I'm not a comfortable php coder so I just did it easiest for me.

    <?php
    $custom_query = new WP_Query('category_name=cat1'); // only Cat1 category
    while($custom_query->have_posts()) : $custom_query->the_post(); ?>
    <div class="posts">
    <?php the_excerpt() ?>
    </div>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); // reset the query ?>
    
    <?php
    $custom_query = new WP_Query('category_name=cat2'); // only Cat2 category
    while($custom_query->have_posts()) : $custom_query->the_post(); ?>
    <div class="posts">
    <?php the_excerpt() ?>
    </div>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); // reset the query ?>
    
    <?php
    $custom_query = new WP_Query('category_name=cat3'); // only Cat3 category
    while($custom_query->have_posts()) : $custom_query->the_post(); ?>
    <div class="posts">
    <?php the_excerpt() ?>
    </div>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); // reset the query ?>
    
    <?php
    $custom_query = new WP_Query('category_name=cat4'); // only Cat4 category
    while($custom_query->have_posts()) : $custom_query->the_post(); ?>
    <div class="posts">
    <?php the_excerpt() ?>
    </div>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); // reset the query ?>

    This is the standard code on the single-loop page for a previous and next post link function:

    <div id="nav-above" class="navigation">
    <div class="nav-previous">
    <?php if (get_previous_post(false) != null): ?>
    <?php previous_post_link( '%link', '< Previous' ); ?>
    <?php else: ?>
    	< Previous
    <?php endif ?>
    </div>
    <span class="main_separator">/</span>
    <div class="nav-next">
    <?php if (get_next_post(false) != null): ?>
    <?php next_post_link( '%link', 'Next >' ); ?>
    <?php else: ?>
    	Next >
    <?php endif ?>
    </div>

Topic Closed

This topic has been closed to new replies.

About this Topic