views:

102

answers:

4
<?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!

+1  A: 

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;
Farinha
A: 

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!

st4ck0v3rfl0w
+2  A: 

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' );
postpostmodern
You just taught me something VERY valuable, thank you. I had no idea up until 5 seconds ago that the 'posts_where' action existed. :D
dskvr
THANKS A TON! That worked like a charm! :)
Nimbuz
A: 

Is this also possible to do for pages?

rayne
You don't "answer" to write your own question, use "comment" for it.
Nimbuz