WordPress自定义分类术语标题搜索配置及报错解决
问题需求
我有一个名为rejectedpayments的自定义文章类型(CPT),并为其分配了rejpayments-category自定义分类法。归档模板仅展示该分类法下的所有术语标题(而非文章),点击术语可查看对应分类下的文章。但当前搜索框仅针对rejectedpayments的文章进行搜索,我需要修改为仅搜索分类术语标题,同时解决之前使用方案时出现的两个报错:
wpdb::prepare调用错误(缺少占位符)- 语法错误(意外的
...运算符)
解决方案
1. 修改搜索表单
删除原表单中指定文章类型的隐藏字段,添加自定义标识参数,区分术语搜索和普通文章搜索:
<form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform"> <div class="row form-wrap"> <div class="col-md-10 padding-none"> <input type="text" name="s" placeholder="Search rejected payment categories"/> <!-- 替换post_type为自定义参数,标记是搜索分类术语 --> <input type="hidden" name="search_terms" value="rejpayments-category" /> </div> <div class="col-md-2 padding-none"> <input type="submit" alt="Search" value="Search" /> </div> </div> </form>
2. 修改归档模板的术语查询逻辑
在归档页面开头添加搜索处理逻辑,根据搜索关键词过滤分类术语,同时修复报错问题:
<?php // 处理搜索请求,过滤并转义关键词 $search_query = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : ''; $taxonomy = 'rejpayments-category'; // 基础术语查询参数 $term_args = array( 'hide_empty' => 0, 'parent' => 0, ); // 如果有搜索关键词,查询匹配的术语ID if (!empty($search_query)) { global $wpdb; // 用规范的prepare语句,添加占位符避免SQL注入 $term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE name LIKE %s OR slug LIKE %s", '%' . $wpdb->esc_like($search_query) . '%', '%' . $wpdb->esc_like($search_query) . '%' ) ); // 根据匹配结果调整查询参数 if (!empty($term_ids)) { $term_args['include'] = $term_ids; } else { // 无匹配时返回空结果 $term_args['include'] = array(0); } } // 获取最终的术语列表 $wcatTerms = get_terms($taxonomy, $term_args); ?> <!-- 术语展示循环 --> <?php if (!empty($wcatTerms)) : ?> <?php foreach($wcatTerms as $wcatTerm) : ?> <div class="results-table"> <div class="row info-tables"> <div class="col-md-6"> <a href="<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>"><?php echo $wcatTerm->name; ?></a> <?php $wsubargs = array( 'hierarchical' => 1, 'show_option_none' => '', 'hide_empty' => 0, 'parent' => $wcatTerm->term_id, 'taxonomy' => $taxonomy ); // 子分类同样应用搜索过滤 if (!empty($search_query)) { $sub_term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE name LIKE %s OR slug LIKE %s", '%' . $wpdb->esc_like($search_query) . '%', '%' . $wpdb->esc_like($search_query) . '%' ) ); if (!empty($sub_term_ids)) { $wsubargs['include'] = $sub_term_ids; } else { $wsubargs['include'] = array(0); } } $wsubcats = get_categories($wsubargs); foreach ($wsubcats as $wsc): ?> <p><a href="<?php echo get_term_link( $wsc->slug, $wsc->taxonomy );?>"><?php echo $wsc->name;?></a></p> <?php endforeach; ?> </div> <div class="col-md-6"> LINK </div> </div> </div> <?php endforeach; ?> <?php else : ?> <p>No categories found matching your search.</p> <?php endif; ?>
3. 报错修复说明
- wpdb::prepare占位符错误:原代码未使用
%s等占位符传递参数,现在的查询严格遵循WordPress规范,用占位符替代直接字符串拼接,同时通过$wpdb->esc_like处理搜索关键词,避免SQL注入。 - Parse error: unexpected '...':该错误是因为PHP版本低于5.6不支持可变参数展开运算符,现在的代码完全使用传统参数传递方式,兼容低版本PHP环境。
内容的提问来源于stack exchange,提问作者jfar_2020
相关产品推荐
相关产品推荐

