如何为分类法字母分页项在无对应术语时添加disabled属性?
给自定义分类法字母分页按钮添加disabled属性(无对应术语时)
要实现只给有对应术语的字母按钮保留可点击状态,无术语的按钮添加disabled属性,你需要在生成按钮前先查询每个字母下是否存在对应术语,再根据结果调整按钮的属性和样式。
修改后的完整代码
function alpha_pagination() { // 替换成你的自定义分类法slug $taxonomy = 'your_custom_taxonomy'; $letters = array( 'A' => __('A', 'your-text-domain'), 'B' => __('B', 'your-text-domain'), 'C' => __('C', 'your-text-domain'), 'D' => __('D', 'your-text-domain'), 'E' => __('E', 'your-text-domain'), 'F' => __('F', 'your-text-domain') ); $html = ''; // 获取当前选中的字母(从URL参数获取) $current_order = isset($_GET['sortby']) ? sanitize_text_field($_GET['sortby']) : ''; foreach ($letters as $key => $value) { // 查询当前字母开头的术语数量 $terms = get_terms(array( 'taxonomy' => $taxonomy, 'hide_empty' => true, // 只统计关联了内容的术语 'name__like' => $key, // 如果需要严格匹配首字母(区分大小写的话用下面的正则匹配) // 'meta_query' => array( // array( // 'key' => 'name', // 'value' => '^'.$key, // 'compare' => 'REGEXP', // 'type' => 'CHAR' // ) // ) )); $has_terms = !empty($terms); // 处理按钮状态 $active_class = ($current_order == $key) ? 'selected' : ''; $disabled_attr = $has_terms ? '' : 'disabled'; $button_class = 'button ' . $active_class . (!$has_terms ? ' disabled-btn' : ''); // 无术语时移除跳转链接 $href = $has_terms ? get_permalink() . '?sortby=' . $key : 'javascript:void(0)'; $html .= '<a class="' . esc_attr($button_class) . '" href="' . esc_url($href) . '" ' . $disabled_attr . '>' . esc_html($value) . '</a>'; } echo $html; }
关键说明
- 替换分类法slug:把
$taxonomy = 'your_custom_taxonomy';中的值改成你实际使用的自定义分类法的slug。 - 术语查询逻辑:
- 使用
get_terms查询对应字母的术语,hide_empty => true确保只统计关联了内容的术语 - 如果需要严格区分大小写的首字母匹配,可以注释掉
name__like,改用meta_query的正则匹配方式
- 使用
- 按钮状态处理:
- 无术语时添加
disabled属性,同时给按钮加自定义类disabled-btn方便编写禁用样式 - 无术语时把
href改成javascript:void(0),避免用户点击跳转无效页面
- 无术语时添加
- 安全处理:使用
sanitize_text_field、esc_attr、esc_url、esc_html确保输出内容符合WordPress安全规范,避免XSS风险
额外样式建议
可以给禁用状态的按钮加CSS样式,提升用户体验:
.button.disabled-btn { opacity: 0.5; cursor: not-allowed; pointer-events: none; }
内容的提问来源于stack exchange,提问作者Mario Grossi
相关产品推荐
相关产品推荐

