簡體   English   中英

向查詢添加范圍以根據首字母獲取帖子

[英]Add a range to a query to get posts based on first letter

我嘗試根據標題的第一個字母查詢帖子,從這個線程開始獲取所有以字母 A 開頭的帖子我有一個版本正在工作但想添加一個范圍,例如返回以 A 到H

<?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>

您可以只使用 $wpdb->get_results 來獲取您的帖子並在一個循環中完成。 然后只需 output 您的結果,並設置一個計數器/增量以將第一個字母顯示為標題。 您可能可以從這里更新...

<?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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM