0

I'm trying to output the current post categories for my 'portfolio' custom post type as a shortcode.

At the moment I have this snippet in the functions.php

    function shows_cats(){
    $page_id = get_queried_object_id();
    echo '<h6>Categories</h6>';
    echo get_the_category_list('','',$page_id);
   }
   add_shortcode('showscats','shows_cats');

I've tried a few different combinations to call the CPT but have had no luck. I realise that this snippet is just outputting standard WP categories but was wondering if anyone knew a way to edit this to display the CTP instead.

Many thanks for your help

2 Answers 2

0

You could try something like this:

// Get the taxonomy's terms
$terms = get_terms(
    array(
        'taxonomy'   => 'your-taxonomy',
        'hide_empty' => false,
    )
);

// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
    // Run a loop and print them all
    foreach ( $terms as $term ) { ?>
        <a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
            <?php echo $term->name; ?>
        </a><?php
    }
} 
0

Thanks for the reply.

I've had another look into this and got something that works as a shortcode but not perfectly. Added the following to my functions.php file and using [showscats] as my shortcode in WPBakery it outputs the current custom post type taxonomies as a list. My CPT taxonomies being "project-type".

The only issue is that it shows all categories that belong to the CPT and not the ones applied to the current post.

// First we create a function
    function shows_cats( $atts ) {

// Inside the function we extract custom taxonomy parameter of our shortcode
 
    extract( shortcode_atts( array(
        'custom_taxonomy' => 'project-type',
    ), $atts ) );
 
// arguments for function wp_list_categories
    $args = array( 
    taxonomy => $custom_taxonomy,
    title_li => ''
    );
// We wrap it in unordered list 
    echo '<ul class="portfolio-cats">'; 
    echo wp_list_categories($args);
    echo '</ul>';
    }
// Add a shortcode that executes our function
    add_shortcode( 'showscats', 'shows_cats' );

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.