获取以字母A开头的所有帖子

时间:2015-07-30 06:12:02

标签: wordpress wp-query

如何以字母A开头(在post_title中)?

我的想法是使用正则表达式,但这段代码不起作用。

$my_custom_query_args = array(

                'cat'               => '1',
                'post_type'         => 'post',
                'post_status'       => 'publish',                
                'posts_per_page'    => 25,
                'offset'            => 0, 
                'value'             => '^'.$letter.'',
                'compare'           => 'REGEXP'

);  

1 个答案:

答案 0 :(得分:4)

使用post_where,此操作代码可用于自定义模板。

add_action( 'posts_where', 'startswithaction' );
function startswithaction( $sql ){
    global $wpdb;
    $startswith = get_query_var( 'A' );

    if( $startswith ){
        $sql .= $wpdb->prepare( " AND $wpdb->posts.post_title LIKE %s ", $startswith.'%' );
    }

    return $sql;
}

或者您可以通过SQL查询以字母A开头获取所有记录,并在WP_QUERY中传递帖子ID。

//get all post IDs for posts start with letter A, in title order,
//display posts
global $wpdb;
$first_char = 'A';
$postids = $wpdb->get_col($wpdb->prepare("
SELECT      ID
FROM        $wpdb->posts
WHERE       SUBSTR($wpdb->posts.post_title,1,1) = %s
ORDER BY    $wpdb->posts.post_title",$first_char)); 

if ($postids) {
$args=array(
  'post__in' => $postids,
  'post_type' => 'post',
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
 echo 'List of Posts Titles beginning with the letter '. $first_char;
  while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
    <?php
  endwhile;
}
wp_reset_query();
}