With this loop I am displaying single posts on an archive page. The posts are being sorted by the category ‘Banks’. In addition to that, how can I display them in alphabetical order? I’ve tried using WP_Query, but cannot get it to work; it breaks my loop each time.

<h3>Banks & Credit Unions</h3>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); 
    if ( in_category( 'Banks' ) ) { ?>
        <li>
            <a href="https://wordpress.stackexchange.com/questions/210817/<?php the_permalink() ?>">
                <img  src="<?php the_field( 'biller_logo' )?>">
                <?php the_field( 'biller_name' ) ?>
            </a>
        </li>
    <?php } 
endwhile; endif; ?>
</ul>

2 s
2

To display posts in descending alphabetical order add this to your args array (taken from the wp codex)

'orderby' => 'title',
'order'   => 'DESC',

To display posts in ascending alphabetical order just switch DESC to ASC.

So the whole thing would look like:

$args = array(
    'orderby' => 'title',
    'order'   => 'DESC',
);
$query = new WP_Query( $args );

WP_Query Order by Parameters

Or to use if you do not want to alter the main loop use get_posts. WP query alters the main loop by changing the variables of the global variable $wp_query. get_posts, on the other hand, simply references a new WP_Query object, and therefore does not affect or alter the main loop. It would be used in the same way, but changing $query = new WP_Query( $args ); to something like $query = get_posts( $args );.

If you would like to alter the main query before it is executed, you can hook into it using the function pre_get_posts.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *