0

I have a small function to get post categories from a custom taxonomy and modify their url, but now I have multi-word categories I need to modify it to use the category slug instead of just the category name. How would I change this to introduce $term->slug somewhere?

$terms = strip_tags( get_the_term_list( $post->ID, 'portfolio_cat', '', '/' ));
$terms = explode("/",$terms);
for($i=0; $i<count($terms); $i++){ 
  echo "<a href='urlhere/$terms[$i]'>" . $terms[$i] . "</a>";
  $total = count($terms) - 1;
  if ($i != $total) { echo', '; }
}
1
  • Please update your question to show how your output currently looks and how you would like it to look.
    – David Gard
    Commented Feb 25, 2015 at 9:23

1 Answer 1

0

While I can't guarentee that this is what you are looking for (as you have not posted what your expected output should be), hopefully this will help.

Even if it's not exactly what you are looking for, you have the whole object for each term available to you so that you can manipulate the output exactly as you wish.

/** Grab the terms within the for the 'portfolio_cat' taxonomy for the current post */
$terms = wp_get_object_terms($post->ID, 'portfolio_cat'); // If you are in The Loop you can replace '$post->ID' with 'get_the_ID()'

/** Loop through each term and add them to an array */
$formatted_terms = array();
foreach($terms as $term) :

    $formatted_terms[] = sprintf(
        '<a href="urlhere/%1$s" title="View posts in $2%s">%3$s</a>',
        $term->slug,            /** %1$s - The term slug (for the 'href' attribute)*/
        esc_attr($term->name),  /** %2$s - The term name (formatted for the 'title' attribute) */
        $term->name             /** %1$s - The term name (for display) */
    );

endforeach;

/** Output the terms, formatted as you desire */
echo join(',', $formatted_terms);

The function that is used to achieve your desired output is wp_get_object_terms(). If you require, you can pass a 3rd parameter as an array containing arguments to order the terms and to only retrun certain fields, so please take a look at the Function Reference.

With the code above the $temrs are returned as an array of objects, and should you wish to use any more of the fields returned for each term here is how the object is formatted -

[0] => stdClass Object
    (
        [term_id] => 22
        [name] => My Taxonomy Term
        [slug] => my-taxonomy-term
        [term_group] => 0
        [term_taxonomy_id] => 29
        [taxonomy] => portfolio_cat
        [description] => 
        [parent] => 20
        [count] => 5
        [filter] => raw
    )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.