Display Posts of a Category in Alphabetical Order (Custom Post Type)

  1. I have a custom post type called “link”
  2. I have a custom taxonomy for this post type called “link-category”
  3. I have a template file for this taxonomy, “taxonomy-link-category.php”
  4. I need the template to display the posts of the selected link category in alphabetical order

EDIT: On the LINKS page of the website all of the category names for the custom post type LINK are displayed in a list. Once a visitor clicks a category name I need wordpress to list all the posts in that category, in alphabetical order. I have it working, with the code below (using template file: taxonomy-link-category.php), but the posts are displayed chronologically, and only 10 of them (the wordpress default).

I’ve tried things like this: Displaying a custom post type alphabetically but of course it displays… EDIT: all of the LINK posts, not just the posts of the selected LINK category.

Read More

This is my current code in taxonomy-link-category.php, can I not just add 'orderby' => 'title', 'order' => 'ASC' somewhere/somehow?

<?php get_header(); ?>
  <div id="content">                    
    <h1>Links</h1>
    <h2><?php echo get_queried_object()->name; ?></h2>
    <?php if (have_posts()) :   // start the loop ?>                    
        <?php while (have_posts()) : the_post(); // loop the posts ?>
            <h3><?php the_title(); ?></h3>
            <?php the_content(); ?> 
        <?php endwhile;     // stop looping the posts ?>                                
        <?php else :        // what to do if there are no posts to show ?>
        <h3>No posts</h3>
    <?php endif;        // end the loop  ?>
  </div><!-- #content -->
<?php get_footer(); ?>

Related posts

Leave a Reply

2 comments

  1. Use the pre_get_posts action to modify the query before it is run. Place this in your theme’s functions.php:

    function wpd_tax_alpha( $query ) {
        if ( $query->is_tax('link-category') && $query->is_main_query() ) {
            $query->set( 'orderby', 'title' );
            $query->set( 'order', 'ASC' );
        }
    }
    add_action( 'pre_get_posts', 'wpd_tax_alpha' );
    
  2. Yes. But I’m afraid I am misunderstanding your intent.

    Have you tried:

    $args = array( 
        'post_type' => 'link', 
        'tax_query' => array(
        array(
            'taxonomy' => 'link-category',
            'field' => 'slug',
            'terms' => array( 'Birds', 'Cats', 'Dogs' )
        )
        ),
        'orderby' => 'title',
        'order' => 'ASC' 
        );
    $query = new WP_Query($args);
    

    That should produce an alphabetically sorted list where the array of terms is present in link-category taxonomy.

    **EDIT original code was missing a comma after the terms array.