2

I have a bunch of categories with sub-categories and sub-sub-categories that I want to list on my archive.php. The titles of the sub-categories are listed on the archive page of its parent category.

Just list the linked titles of the categories and/or posts, nothing more. Everything works perfectly, but on the last step I'd like to order the actual posts alphabetically.

So I have this code in my archive.php

<?php
if (is_category()) {
    $this_category = get_category($cat);
}

$this_category = wp_list_categories('orderby=name&depth=1&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");

if ($this_category && $catlvl !=0) { ?> 
    <ul class="cat_options">
<?php 
if ($catlvl !=3){
    if ($catlvl == 1){
        // Do stuff
    }
    if ($catlvl == 2){
        // Do stuff
    }
} else {
    // Do stuff
    $wpex_count = 0;
    while ( have_posts() ) : the_post();
        $wpex_count++;

        // Get entry title ?>
        <li>
        <a href="<?php wpex_permalink(); ?>" title="<?php wpex_esc_title(); ?>" rel="bookmark"><?php the_title(); ?></a>
        </li> <?php                            

        // Reset counter to clear floats
        if ( wpex_blog_entry_columns() == $wpex_count ) {
            $wpex_count=0;
        }

    endwhile;
}
?>
</ul>
<?php }

How do I make it so it lists the posts alphabetically on the last step? On the pages where it lists categories they are in alphabetical order.

Can I use

$args = array( 'posts_per_page' => -1, 'orderby'=> 'title', 'order' => 'ASC' );

from https://codex.wordpress.org/Alphabetizing_Posts here somehow? How? Or do I need to get my posts in some other way?

Only posts in the current category should be listed. When I use the method in the link above it lists ALL posts in ALL categories.

1 Answer 1

1

I suggest you use the pre_get_posts action hook provided by WordPress.

Then, in your functions.php add the following code below:

function custom_pre_get_posts($query) {
    // validate
    if(!is_admin() && $query->is_main_query()) {

        if(is_archive()) {
            $query->set('orderby', 'title'); // order posts by title
            $query->set('order', 'ASC'); // and in ascending order
        }
    }
}
add_action('pre_get_posts', 'custom_pre_get_posts');

You can learn more about pre_get_posts in here

1
  • 1
    That solved it! Thanks so much. I didn't have to change my code or anything, just added that to my functions.php and it worked.
    – Shmiiiii
    Commented Jun 19, 2017 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.