【问题标题】:Add a range to a query to get posts based on first letter向查询添加范围以根据首字母获取帖子
【发布时间】:2026-01-31 13:05:01
【问题描述】:

我尝试根据标题的第一个字母查询帖子,从这个线程Get all posts beginning with letter A 开始

<?php 

//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' => 'links',
  '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() ) { ?>
    
    <ul id="listhome">  
     
     <?php /*?><?php echo 'List of links beginning with the letter '. $first_char;?><?php */?>
  
  <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <li class="threehomecolist spacer10"> <?php 
$link = get_field('links_resources'); //external link
if( $link ): ?>
    <a href="<?php echo esc_url( $link ); ?>" target="_blank" rel="nofollow"><?php the_title(); ?></a>
    <?php echo '<hr class="new2">' ?>
<?php endif; ?></li>
    <?php
  endwhile;
}
wp_reset_query();
} ?>
    
    </ul>

【问题讨论】:

  • 您只需使用 range('A','H') 从 A-H 创建一个范围,然后使用 WHERE ... IN 查询而不是 =。

标签: php wordpress custom-post-type


【解决方案1】:

您可以只使用 $wpdb->get_results 来获取您的帖子并在一个循环中完成。然后只需输出您的结果,并设置一个计数器/增量以将第一个字母显示为标题。您可能可以从这里更新...

<?php 
global $wpdb;
// The Query
$sql = "
    SELECT      *
    FROM        $wpdb->posts
    WHERE       SUBSTR($wpdb->posts.post_title,1,1) IN ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
    AND post_status = 'publish' AND post_type = 'link'
    ORDER BY    $wpdb->posts.post_title;";

$my_query = $wpdb->get_results( $sql );

if ( $my_query ) {
$prev_first = '';    
  ?>
<ul id="listhome">
  <?php foreach ($my_query as $post) :
    // Get the first Character
    $first_char = strtoupper(substr($post->post_title, 0, 1));
    // Compare and show or not heading row
    if ($first_char !== $prev_first) {
        $show_first = true;
    } else {
        $show_first = false;
    }
    $prev_first = $first_char;
  if ($show_first) : ?>
      <h3>List of links beginning with the letter <?php echo $first_char; ?></h3>
  <?php endif;?>
  <li class="threehomecolist spacer10">
    <?php
    $link = get_field('links_resources', $post->ID);    
    if ( $link ): ?>
    <a href="<?php echo esc_url( $link ); ?>" target="_blank" rel="nofollow">
    <?php the_title(); ?>
    </a> <?php echo '<hr class="new2">' ?>
    <?php endif; ?>
  </li>
  <?php
  endforeach;
  }
  wp_reset_query();
  ?>
</ul>

【讨论】: