I have a custom taxonomy alphabetical pagination to list terms by first letter.
function alpha_pagination() {
$array = array(
'A' => __('A',''), 'B' => __('B',''), 'C' => __('C',''),
'D' => __('D',''), 'E' => __('E',''), 'F' => __('F','')
);
$html = '';
foreach ( $array as $key=>$value ){
$active = ( $order == $key ) ? 'selected' : null;
$html .= '<a class="button '.$active.'" href="'.get_permalink().'? sortby='.$key.'">'.$value.'</a>';
}
print $html;
}
When I print the function on the taxonomies list page everything works good but the buttons from a to z are all clickable even if the term is empty. What I’m trying to do is adding the disabled attribute to letters without terms.
2
Answers
To add the disabled attribute to empty alphabetical pagination items, you need to check if there are any terms for each letter before rendering the link/button
terms beginning with each letter using the get_terms function, and
then apply the disabled class.
you can do something like this
In your function, you will need to first iterate through all terms in your taxonomy and populate an array of A-Z letters (and potentially any other leading characters not represented by A-Z). For each unique leading character, ensure that value/flag relating to the uppercase version of the character is set to
true
to indicate that that character has at least one term. You do not need to actually retain all of the terms while building the lookup array.Then iterate over the updated array and print your HTML elements with the desired conditional attributes.
printf()
is a good tool because it minimizes concatenation and allows placeholders to access the same variable in multiple places.Be sure to multibyte-safe functions and encode/escape HTML entities to avoid unexpected bugs from fringe-case values.
Code: (Demo)
Or if you prefer separate
printf()
calls: (Demo)