Alphabetical sorting inside loop
-
Hi. I have a liitle trouble with code which I found over the internet. Basicly I wanted list my posts by first letter of title.
For example: A: Adam Alex Alvin Arnold B: Bilbo Barney Benjamin C: Cameron .... .... etc.<?php $args = array ( 'post_type' => 'post', 'posts_per_page' => -1, 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' ); $my_query = new WP_Query($args); if( $my_query->have_posts() ) { echo '<div"><ul>'; while ($my_query->have_posts()) : $my_query->the_post(); $definite_article = array('The ', 'A ', 'An '); $pattern = '/\b(?:' . join('|', $definite_article) . ')\b/i'; $post_title = $post->post_title; $post_title = preg_replace($pattern, '', $post_title); $this_char = strtoupper(substr($trailer_title,0,1)); if ($this_char != $last_char) { $last_char = $this_char; echo '<li><h2>'.$last_char.'</h2>'; } ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php echo $post_title; ?></a> <?php endwhile; echo '</li></ul></div>'; } wp_reset_query(); ?>This code works well, but I want to add few more improvements. As you may notice, from post title it removes definite article such as “The”, “An” and “A”, but if the post have title “A Nice…”, post listing will start from letter “N”, not “A”. How re-sort post alphabetically inside loop and correctly assigns letters?
Any kind of help will suffice.
Thx.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
The topic ‘Alphabetical sorting inside loop’ is closed to new replies.