Get all posts beginning with letter A

浪子不回头ぞ 提交于 2020-01-06 03:10:28

问题


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:


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


来源:https://stackoverflow.com/questions/31716312/get-all-posts-beginning-with-letter-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!