Tutorial :Fetch posts starting with alphabet [x]



Question:

<?php $temp_query = $wp_query; ?>  <?php query_posts('tag=sometag,anothertag&posts_per_page=10'); ?>    <?php while (have_posts()) : the_post(); ?>    // print post here  <?php endwhile; ?>    <?php $wp_query = $temp_query; ?>  

Using this simple wordpress loop, how do I show ONLY the posts (post titles actually) starting with say letter 'G'. I want to sort posts alphabetically but only those that matches, not all.

Thanks!


Solution:1

I would set up an action for the query. In your themes functions.php file:

add_action( 'posts_where', 'startswithaction' );  function startswithaction( $sql ){      global $wpdb;      $startswith = get_query_var( 'startswith' );        if( $startswith ){          $sql .= $wpdb->prepare( " AND $wpdb->posts.post_title LIKE %s ", $startswith.'%' );      }        return $sql;  }  

Then you can query the posts like so:

query_posts( 'startswith=G&posts_per_page=10' );  


Solution:2

Check the post title inside the loop:

while (have_posts()) : the_post();      // jump to the next post if this one doesn't start with the letter you want      if($post->post_title[0] != $letter) continue        // do what you want with the post  endwhile;  


Solution:3

Crazy thought here, but why dont you just add the Letter as a Tag to the post. In other words, if you wanted your post "The Beautiful Trees" to show up under "B" (note that I said B and not T), simply apply the tag called "B". Then in you query posts tag section, just make sure you append your letter of choice!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »