Created
November 27, 2020 15:16
-
-
Save neverything/5dc2d34d1d2bb46e96551df57549c629 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Shortcode: [pp_tax_list] to render an unlinked list of taxonomy terms assigned | |
* to the current object. | |
* | |
* How to use: [pp_tax_list tax='<taxonomy>'] | |
* Optional params are: | |
* display='list|string' defaults to list | |
* wrapper_class='pp-tax-list' any css classes that are needed on the wrapper div. | |
* | |
* @param array $atts attributes for the shortcode function. | |
* @param null $content there is no content for this shortcode. | |
* | |
* @return string|void | |
*/ | |
function tax_to_list_shortcode( $atts, $content = null ) { | |
/** | |
* Merge default attributes with the attributes provided in the shortcode. | |
*/ | |
$attributes = shortcode_atts( [ | |
'tax' => 'category', | |
'display' => 'list', | |
'wrapper_class' => 'pp-tax-list', | |
], $atts ); | |
/** | |
* Bail silently if we don't have a working taxonomy. | |
*/ | |
if ( ! taxonomy_exists( $attributes['tax'] ) ) { | |
return; | |
} | |
/** | |
* Get the object ID for the current post type. | |
*/ | |
$object_id = get_the_ID(); | |
/** | |
* Get the post type of the current object. | |
*/ | |
$object_type = get_post_type( $object_id ); | |
/* | |
* Setup fallback message when no terms exists for this object ID. | |
*/ | |
$terms_output = "There are no terms in {$attributes['tax']} for {$object_type} with ID {$object_id}"; | |
/** | |
* Get the actual terms for the object and taxonomy. | |
*/ | |
$terms = get_the_terms( $object_id, $attributes['tax'] ); | |
/** | |
* Only prepare rendering if we have terms. | |
*/ | |
if ( ! is_a( $terms, 'WP_Error' ) && false !== $terms ) { | |
switch ( $attributes['display'] ) { | |
case 'string': | |
$terms_output = join( ', ', wp_list_pluck( $terms, 'name' ) ); | |
break; | |
case 'list': | |
default: | |
$terms_output = '<ul><li>' . join( '</li><li>', wp_list_pluck( $terms, 'name' ) ) . '</li></ul>'; | |
break; | |
} | |
} | |
$output_start = "<div class='{$attributes['wrapper_class']}'>"; | |
$output_end = "</div>"; | |
return $output_start . $terms_output . $output_end; | |
} | |
add_shortcode( 'pp_tax_list', 'tax_to_list_shortcode' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment