How to add a-z filter to wordpress search result?

2019-06-10 03:44发布

I need to filter my search result alphabetically for example at the head of the search result page there will be list of letters A - B - C - .... - Z - ALL

and when I click on any letter the result show me the posts that only start with that letter

1条回答
祖国的老花朵
2楼-- · 2019-06-10 04:28

in the search.php on your theme

before the loop add

    <?php 

add_action( 'posts_where', 'startswithaction' );
function startswithaction( $sql ){
    global $wpdb;
    $startswith = get_query_var( 'startswith' );

    if( $startswith ){
        $sql .= $wpdb->prepare( " AND $wpdb->posts.post_title LIKE %s ", $startswith.'%' );
    }

    return $sql;
}
add_action( 'posts_where', 'startswithnumberaction' );
function startswithnumberaction( $sql ){
    global $wpdb;
    $startswithnumber = get_query_var( 'startswithnumber' );

    if( $startswithnumber ){ 
        $sql .= $wpdb->prepare( " AND $wpdb->posts.post_title NOT REGEXP %s ", '^[[:alpha:]]' );
    }

    return $sql;
}

query_posts( $query_string .'&startswith='.$_GET['letter'].'&posts_per_page=-1&startswithnumber='.$_GET['number']);
?>

</code>

and then add your links

echo "<a href='$PHP_Self/?$query_string&number=true' ># </a> - ";


    foreach (range('A', 'Z') as $i)
    {
     $letter =strtolower($i);
        echo "<a href='$PHP_Self/?$query_string&letter=$letter' >$i </a> - ";
    }
    echo "<a href='$PHP_Self/?$query_string' >All </a>

like that when u click on any letter the search result will be filtered to the posts that only starts with this letter

查看更多
登录 后发表回答