WordPress如何查询所有标题以非a-z特殊符号开头的文章
调整方案
你可以通过扩展原有的自定义查询钩子,新增正则匹配逻辑实现需求,无需删除原有功能,兼容你之前的首字母查询逻辑:
步骤1:修改主题functions.php中的过滤函数
将原有wpse_298888_posts_where函数替换为如下代码:
function wpse_298888_posts_where( $where, $query ) { global $wpdb; $starts_with = esc_sql( $query->get( 'starts_with' ) ); // 新增自定义参数标记:是否查询非a-z开头的文章 $non_alpha_start = $query->get( 'non_alpha_start' ); if ( $starts_with ) { $where .= " AND $wpdb->posts.post_title LIKE '$starts_with%'"; } // 新增非字母开头的查询条件 if ( $non_alpha_start ) { // 正则匹配标题首字符不是a-z、A-Z的内容,自动兼容数字、中文、特殊符号等场景 $where .= " AND $wpdb->posts.post_title REGEXP '^[^a-zA-Z]'"; } return $where; } add_filter( 'posts_where', 'wpse_298888_posts_where', 10, 2 );
步骤2:调整你的查询参数代码
将原有查询部分的参数改为如下写法即可:
<?php $args = array( 'posts_per_page' => -1, 'non_alpha_start' => true, // 启用非a-z开头的查询规则 'post_type' => 'artists' ); $the_query = new WP_Query( $args ); while( $the_query->have_posts() ) : $the_query->the_post(); ?> <!-- 此处写你的文章输出逻辑 --> <?php endwhile; // 用完记得重置post数据,避免影响后续查询 wp_reset_postdata(); ?>
补充说明
- 如果你数据库的排序规则本身是大小写不敏感的,正则部分可以简化为
'^[^a-z]',效果一致 - 该修改不会影响你之前使用
starts_with参数查询指定首字母文章的逻辑,两种模式可以共存
内容的提问来源于stack exchange,提问作者public9nf
相关产品推荐
相关产品推荐

