WordPress Custom Post Type Listing by Alphabets with Alphabetical Navigation

wordpress-media

Usually, in a WordPress blog or website, we do not need to list posts or pages by alphabetical order but with more and more people using the Custom Post Types and adding topics and sections in their website which do need alphabetical listing such as a if you have created Custom Post Type for Movies, Models, Designers, Celebs or Books, showing these by alphabetical order on their separate pages for each letter becomes very attractive and natural requirement.

First of all, we need to create alphabet navigation on top of page for the posts list to display on separate pages for each letter. Add following function in the theme functions.php file:

 
function get_alphabet_nav($sef=''){
 
   $url_array = explode('/', $_SERVER['REQUEST_URI']); 
   $folder = $url_array[sizeof($url_array)-2];
 
   $base='http://'.$_SERVER['HTTP_HOST'].'/';
   $sef = $sef.'/';
 
   $path= $_SERVER['REQUEST_URI'];
 
   for ($i=65; $i<=90; $i++) {
    $x = chr($i);
    $nav .= '<a href="'.$base.$sef.strtolower($x).'/">'.$x.'</a>'."\n";
   }
 return $nav;
}

Now create a new file by copying the page.php file available in your theme folder and name it as page-book.php (assuming your CPT is book) add following code at top of page before the while loop:

 
 echo '<h2>Custom Post Type Alphabetical Listing</h2>
 
<div id="alphaList" align="center">'.get_alphabet_nav('listing-page-slug-here').'</div><br />';
//replace listing-page-slug-here with the one you have used for creating page.
//such as books-listing or designers-listing

On top of this page-book.php, define the name for the template like:

 
/*  Template Name: Custom Post Type (Books) Listing Page  */

In the Books Listing template, find the following loop:

 
 if ( have_posts() ) while ( have_posts() ) : the_post();

Add the following line above the loop:

 
query_posts(array('post_type'=>'book')); /*replace 'book' with your custom post type*/

The Above code will instruct WordPress to find all posts that have the ‘book’ type and loop through them.

Now you have created your Custom Page Template to list books, but you also need to to create “Books” page that will show listing of book type posts using this template you just created. In order to create Page, log in to the WordPress admin panel, create a new page with the title of “Books Listing by Alphabets”, and then select the “Books Listing Template” for the Template page attribute.

You also need to create sub pages for each letter choosing the Books Listing page as parent so that all letter pages become sub pages and their slugs show it. Make sure that your sub page slug is just the letter and it will look like this /books-listing/a/, /books-listing/b/ and so on. You will need to create sub-pages for all 26 letters. Please note that you choose Books Listing Template from the Page Attributes.

To list the Custom Post types for books starting with any letter, you need to check the url of the page and query the WordPress database using REGEXP like this:

 
<?php
 
if( ereg( '/[a-z-]+/[a-z]/$', $_SERVER['REQUEST_URI'])) {
 
$url_array = explode('/', $_SERVER['REQUEST_URI']); 
$alpha = $url_array[sizeof($url_array)-2];
 
$postids = $wpdb->get_col("
    SELECT p.ID
    FROM $wpdb->posts p
    WHERE p.post_title REGEXP '^" . $wpdb->escape($alpha) . "'
    AND p.post_status = 'publish' 
    AND p.post_type = 'book' /*replace 'book' with your custom post type*/
    AND p.post_date < NOW()
    ORDER BY p.post_title ASC"
);
 
 
if ($postids) {
  $args=array(
    'post__in' => $postids,
    'post_type' => 'book', /*replace 'book' with your custom post type*/
    '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() ) {
 
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
 
	<div class="listing">
 
       <h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> </h3>
		<?php the_excerpt(); ?>				
	</div>
 
      <?php
    endwhile;
    }
 
  }
 
}
 else {
	query_posts(array('post_type'=>'book')); /*replace 'book' with your custom post type*/
 
	if (have_posts()) : while (have_posts()) : the_post(); 
 
	 ?>     	 
 
	<div class="listing">
     <h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> </h3>
	<?php the_excerpt(); ?>				
	</div>
 
    <?php endwhile; else: ?>
 
    <p>Sorry, no profiles matched your criteria.</p>
 
   <?php endif; ?>
 
</div> <!-- end post -->
 
<div class="navigation">
 
<?php if (function_exists('wp_pagenavi')) { wp_pagenavi(); } else { ?>
 
<div class="floatleft"><?php next_posts_link( __('&laquo; Older Entries', '') ); ?></div>
<div class="floatright"><?php previous_posts_link( __('Newer Entries &raquo;', '') ); ?></div>
 
  <?php } 
} ?>

css styles for alphaList id:

 
#alphaList { width:600px; overflow:hidden; 
font-size:12px; 
clear:both; border-top:1px solid #E3E3E3;  
border-bottom:3px solid #000000;
}
#alphaList .first { border:0; }
#alphaList a { display:block; line-height:22px; 
width:22px; float:left; text-align:center; 
border-left:1px solid #E3E3E3 
}
 
#alphaList a:hover { background:#f1f1f1;
 text-decoration:none; color:black 
}

Summary of logic and process what you need to do

1. Create a Listing page by copying the page.php in your WordPress theme folder and name it ‘Listing Template’.
2. Create a Page ‘Books Listing by Alphabets’ with a slug ‘/books/’ and select the ‘Listing Template’ you just created from Page Attributes and not the default template.
3. Go on to create few more pages for more letters whose slugs will look like this ‘/books/a/’, ‘/books/b/’ and so on to ‘/books/z/’. Make sure you create all these letter pages as child pages of the Listing page you just created in second step using the same ‘Listing Template’ of step 1. You will have to create sub pages for all 26 letters.
3. Now generate the alphabetical navigation using the function above. That code generates links for each letter page. These links will point to the pages you created in the third step above.
4. Now all you have to do is to catch the letter from the slug and pass it on to the query. I have written all that code already so you just have to copy that code and place inside your template.
5. Just make sure you change the example custom post type ‘book’ to your actual custom post type. I have commented it in the code wherever you need to do this.
6. Also make sure that your custom post type slug is different from your listing page slug, because if you do that, all your CPT records will be considered as sub-pages of the listing page by WordPress. Using above example, if your listing slug is ‘books’, your CPT should be ‘book’ so that WordPress routes those requests to your CPT page.


Hope that helps.

Cheers!

Related posts:

  1. Include & Display Custom Post Type Records under Categories Posts Listing in WordPress
  2. WordPress Custom Post Types – Best Plugin for the Job and How to Set it Up
  3. Resolve Pagination Problem for Custom Post Types Listing in WordPress
  4. Resolve Permalinks 404 Error with Custom Post Type using WordPress
  5. Custom Page Templates Not Showing Up in Page Attributes Drop Down in WordPress Admin Panel