WordPress.org

Ready to get started?Download WordPress

Forums

Order Posts by Alphabetical for Each Letter (2 posts)

  1. auhan
    Member
    Posted 2 months ago #

    I need to order my posts by alphabetical for each letter. I mean:

    When people enter to http://www.xxx.com/a, they will just see posts by starting A.

    ABC XYZ
    ADE KLM
    ARE UYZ

    When people enter to http://www.xxx.com/b, they will just see posts by starting B.

    BCK OIO
    BHJ PEP

    I hope you will understand what I want. I have founded this code:

    <?php
    $last_char = '';
    $args=array(
      'orderby' => 'title',
      'order' => 'ASC',
      'posts_per_page'=>-1,
      'caller_get_posts'=>1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'Alphabetic index of all ' . count($my_query->posts) . ' posts';
      while ($my_query->have_posts()) : $my_query->the_post();
        $this_char = strtoupper(substr($post->post_title,0,1));
        if ($this_char != $last_char) {
          $last_char = $this_char;
          echo '<h2>'.$last_char.'</h2>';
        } ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    } //if ($my_query)
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>

    However, this code lists all posts by alphabetical in one page. As I said before, I just want same thing but for one letter which I specify.

    Thank you for helping me.

  2. auhan
    Member
    Posted 2 months ago #

    I finally find the code what I exactly want. Two codes I find were coded by MichaelH from wordpress.org. Even he won't probably see this post, I want to thank him.

    <?php
    //get all post IDs for posts beginning with cap B, in title order,
    //display posts
    $first_char = 'B';
    
    $postids=$wpdb->get_col($wpdb->prepare("
    SELECT      ID
    FROM        $wpdb->posts
    WHERE       SUBSTR($wpdb->posts.post_title,1,1) = %s
    ORDER BY    $wpdb->posts.post_title",$first_char)); 
    
    if ($postids) {
    $args=array(
      'post__in' => $postids,
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
     echo 'List of Posts Titles beginning with the letter '. $first_char;
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    }
    ?>

Reply

You must log in to post.

About this Topic