获取以字母[x]开头的帖子

3zz*_*zzy 2 php sorting wordpress

<?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; ?>
Run Code Online (Sandbox Code Playgroud)

使用这个简单的wordpress循环,我如何只显示以字母'G'开头的帖子(实际发布标题).我想按字母顺序对帖子进行排序,但只对那些匹配的帖子进行排序

谢谢!

pos*_*ern 5

我会为查询设置一个动作.在你的主题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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样查询帖子:

query_posts( 'startswith=G&posts_per_page=10' );
Run Code Online (Sandbox Code Playgroud)

  • 你告诉我一些非常有价值的东西,谢谢你.直到5秒前我还不知道'posts_where'动作存在.:d (3认同)