<?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 tit开发者_如何学JAVAles actually) starting with say letter 'G'. I want to sort posts alphabetically but only those that matches, not all.
Thanks!
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' );
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;
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!
精彩评论