Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active December 7, 2022 15:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshuadavidnelson/5e9e159e06c19c4a1320 to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/5e9e159e06c19c4a1320 to your computer and use it in GitHub Desktop.
Shortcode to create a list or dropdown link to taxonomy archives
<?php
/**
* Shortcode to create a list or dropdown link to taxonomy archives
*
* @author Joshua David Nelson, josh@jdn.im
**/
function jdn_taxonomy_list( $atts ) {
$a = shortcode_atts( array(
'taxonomy' => '',
'post-type' => 'post',
'type' => 'list',
'title' => '',
), $atts );
$filter_text = '';
// Make sure the taxonomy field is valid and it exists
if( $a['taxonomy'] !== '' && taxonomy_exists( $a['taxonomy'] ) ) {
$taxonomy = get_taxonomy( $a['taxonomy'] );
$tax_url = get_post_type_archive_link( $a['post-type'] ) . '?' . $taxonomy->name . '=';
$taxonomy_name = ucfirst( $taxonomy->labels->name );
if( $a['type'] == 'list' ) {
$filter_text .= '<div class="taxonomy-list taxonomy-' . $taxonomy->name . '">';
if( $a['title'] !== '' ) {
$filter_text .= '<h3 class="info-head">' . $a['title'] . '</h3>';
} else {
$filter_text .= '<h3 class="info-head">Search By ' . $taxonomy->labels->singular_name . '</h3>';
}
$filter_text .= '<ul>';
$args = array(
'orderby' => 'name',
'order' => 'ASC',
);
$terms = get_terms( $taxonomy->name, $args );
foreach( $terms as $term ) {
$filter_text .= '<li><a href="' . get_term_link( $term, $taxonomy->name ) . '" title="' . $term->name . '">' . $term->name . '</a></li>';
}
$filter_text .= '</ul></div>';
} elseif( $a['type'] == 'dropdown' ) {
$filter_text .= '<div class="taxonomy-list taxonomy-' . $taxonomy->name . '"><form name="type_jump">';
if( $a['title'] !== '' ) {
$filter_text .= '<h3 class="info-head">' . $a['title'] . '</h3>';
} else {
$filter_text .= '<h3 class="info-head">Search By ' . $taxonomy->labels->singular_name . '</h3>';
}
$filter_text .= '<select class="input-block-level select" name="' . $taxonomy->name . '" OnChange="window.location=this.options[this.selectedIndex].value;">';
$args = array(
'orderby' => 'name',
'order' => 'ASC',
);
$filter_text .= '<option value="">Select A ' . $taxonomy->labels->singular_name . '</option>';
$terms = get_terms( $taxonomy->name, $args );
foreach( $terms as $term ) {
$filter_text .= '<option value="' . $tax_url . $term->slug . '">' . $term->name . '</option>';
}
$filter_text .= '</select></form></div>';
}
}
return $filter_text;
}
add_shortcode( 'jdn_taxonomy_list', 'jdn_taxonomy_list' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment