获取所有的帖子以字母A开头(Get all posts beginning with letter

2019-10-24 07:27发布

我怎样才能得到所有poasts以字母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'

);  

Answer 1:

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

或者你可以得到所有的记录开始与信A通过SQL查询,并通过后IDS在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();
}


文章来源: Get all posts beginning with letter A