Create dynamically generated and sanitized CSS classes as a list from a taxonomy's terms in Wordpress
<?php
/*
* Create dynamically generated and sanitized CSS classes as a list from a taxonomy's terms
* Example: <a class="<?php echo taxonmy_terms_as_css_list('Geographical Locations'); ?>"
*
*/
function taxonmy_terms_as_css_list($term_name) {
// get the taxonomy terms
$get_terms = get_terms($term_name);
// prepare each taxonomy term as a sanitized CSS class
// 1. store terms in an array
// 2. to lowecase
// 3. replace spaces with dashes (so that spaces can be used in between separate class names)
// 4. replace any NON alphanumeric, underscore or dash characters with a hyphen
foreach ($get_terms as $term) {
$term_list[] = strtolower(str_replace(' ', '-', preg_replace('/[^\w-]/', '-', $term->name)));
}
// join array elements into a single string
$terms = implode(' ', $term_list);
// remove trailing hyphen (if it exists)
$terms = rtrim($terms, '-');
return $terms;
}
?>
<?php
echo taxonmy_terms_as_css_list('YOUR_TAXONOMY'); ?>