Get all posts beginning with letter A

2019-08-10 22:54发布

How can i get all poasts beginning with the letter A (in the post_title)?

My idea was to use regex but this code dont work.

$my_custom_query_args = array(

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

);  

1条回答
Ridiculous、
2楼-- · 2019-08-10 23:41

Using post_where , this action code be use in custom template.

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;
}

OR you can get all records starts with letter A by SQL query and pass the post ids in WP_QUERY.

//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();
}
查看更多
登录 后发表回答