0

I am using a shortcode to try to display the tags and categories of a post. Specifically, this is a portfolio post, so when a user visits a post they will see the associated categories and tags. example here

My shortcode is pulling all portfolio-categorys or portfolio-tags, not just those of the current post.

<?php
class ListCategories{
  static function list_categories($atts, $content = null) {
    $atts = shortcode_atts(
      array(
        'child_of'            => 0,
        'current_category'    => 0,
        'depth'               => 0,
        'echo'                => 1,
        'exclude'             => '',
        'exclude_tree'        => '',
        'feed'                => '',
        'feed_image'          => '',
        'feed_type'           => '',
        'hide_empty'          => 1,
        'hide_title_if_empty' => false,
        'hierarchical'        => 1,
        'include'             => '',
        'number'              => null,
        'order'               => 'ASC',
        'orderby'             => 'name',
        'pad_counts'          => 0,
        'show_count'          => 0,
        'show_option_all'     => '',
        'show_option_none'    => __( 'No categories' ),
        'style'               => 'list',
        'taxonomy'            => 'category',
        'title_li'            => __( 'Categories' ),
        'use_desc_for_title'  => 1,
        'walker'              => null,
      ), $atts
    );

    ob_start();
    wp_list_categories($atts);
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
  }
}

add_shortcode( 'categories', array('ListCategories', 'list_categories') );

1 Answer 1

0

If you're using the default category and post_tag taxonomies for your portfolio posts, then have a look at get_the_tags() and get_the_category(). These will return arrays of tags and categories for the current post. Pass post ID as parameter to the functions, when using outside the Loop.

If on the other hand you have custom taxonomies, then use get_the_terms() directly, for which you can pass the custom taxonomy slug as the 2nd parameter, post ID being the 1st.

If you want to use wp_list_categories(), then you should pass include as one of the parameters so that the list is limited to the given term IDs. There's a nice example on the documentation how to do this with the help of wp_get_object_terms().

2
  • The category taxonomy is portfolio-category. And the posts are portfolio-tag. I assume those are custom taxonomies created by the theme I'm customizing.
    – Georgeand
    Feb 25 at 21:57
  • @Georgeand Yes, I would assume so too. Feb 26 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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