Fetch帖子以字母开头[x]
问题描述:
<?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; ?>
使用这个简单的wordpress循环,我该如何显示仅以字母'G'开头的帖子(实际上是帖子标题)。我想按字母顺序排列帖子,但只匹配那些匹配的,不是全部。Fetch帖子以字母开头[x]
谢谢!
答
我会为查询设置一个操作。在你的主题functions.php文件:
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;
}
然后你就可以查询职位像这样:
query_posts('startswith=G&posts_per_page=10');
答
检查循环内的文章标题:
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;
答
疯狂想到这里,但你为什么不只是添加字母作为标签的帖子。换句话说,如果你想让你的帖子“美丽的树”出现在“B”下(注意我说的是B而不是T),只需使用名为“B”的标签即可。然后在你的帖子标签部分查询,只要确保你附上你的选择信!
你只教了我一些非常有价值的,谢谢。直到5秒钟之前,我还不知道“posts_where”操作是否存在。 :D – Sandwich 2010-02-11 22:45:07
谢谢!这就像一个魅力! :) – 3zzy 2010-02-12 04:56:33
这是一个非常好的解决方案,但我个人不喜欢在任何地方使用原始SQL。奇怪的是,基本的查询帖子参数没有像帖子上的元查询那样的东西有关于'喜欢','不喜欢,等等。 http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters – Foxinni 2012-07-26 14:16:42