WordPress.org

Ready to get started?Download WordPress

Forums

Alphabetical sorting inside loop (2 posts)

  1. titan_rising
    Member
    Posted 1 year ago #

    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.

  2. vtxyzzy
    Member
    Posted 1 year ago #

    I think you can just comment out this line:

    $post_title = preg_replace($pattern, '', $post_title);

    like this:

    // $post_title = preg_replace($pattern, '', $post_title);

    If this is not what you want, see this pastebin article: http://pastebin.com/X6bPHvSY

Topic Closed

This topic has been closed to new replies.

About this Topic