Last active
August 3, 2016 04:08
-
-
Save cezarsmpio/49c843c1f2598b03cb65e91ad3080239 to your computer and use it in GitHub Desktop.
Wordpress - Get the post terms
This file contains hidden or 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 | |
/** | |
* Get the terms of specific post in a list | |
* @param object $p The post | |
* @param array $params An array of params | |
* @return string The HTML result | |
*/ | |
function get_post_terms($p, $params = array()) { | |
$defaults = array( | |
'class' => 'term-item', | |
'separator' => ', ', | |
'taxonomy' => 'category', | |
'links' => true, | |
'args' => array() | |
); | |
$options = array_merge($defaults, $params); | |
$elements = array(); | |
$p->cats = wp_get_post_terms($p->ID, $options['taxonomy'], $options['args']); | |
foreach ($p->cats as $c) { | |
$cat = get_category($c); | |
if ($options['links']) { | |
$elements[] = "<a href=\"" . get_category_link($cat->term_id) . "\" class=\"" . $options['class'] . "\">" . $cat->name . "</a>"; | |
} | |
else { | |
$elements[] = "<span class=\"" . $options['class'] . "\">" . $cat->name . "</span>"; | |
} | |
} | |
return implode($options['separator'], $elements); | |
} | |
/** | |
* Example of use: | |
* | |
* <?php echo get_post_terms($post, array('taxonomy' => 'fields', 'links' => false, 'class' => 'term__item', 'separator' => ' | ')); ?> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment