Search code examples
phpwordpresssidebar

How to display cpt categories in sidebar?


I want to display my cpt categories in sidebar of cpt, my codes as as follows

//add custom menus
function codex_custom_init() {
    register_post_type(
    'Jobs', array(
    'labels' => array('name' => __( 'Jobs' ), 'singular_name' => __( 'Jobs' ) ),
    'public' => true,
    'has_archive' => true,
    'supports' => array('title', 'editor', 'thumbnail'),
    'menu_icon' => 'dashicons-calendar-alt',
    'show_in_rest' => 'true'
     )
     );
}
add_action( 'init', 'codex_custom_init' );

function jobs_create_my_taxonomy() {

    register_taxonomy(
        'jobs-category',
        'jobs',
        array(
            'label' => __( 'Category' ),
            'rewrite' => array( 'slug' => 'jobs-category' ),
            'hierarchical' => true,
            'show_in_rest' => 'true'
        )
    );
}
add_action( 'init', 'jobs_create_my_taxonomy' );

I need to display cpt categories in sidebar with category links.


Solution

  • You can use add_shortcode and get_terms. add show_category to sidebar.

    function show_category(){
    
        $jobs_category = get_terms( array(
            'taxonomy' => 'jobs-category',
            'hide_empty' => false
        ) );
         
        if ( !empty( $jobs_category ) ) {
            $output = '<ul>';
                foreach( $jobs_category as $category ) {
                    $output.= '<li><a href="'.get_term_link( $category ).'">'. esc_attr( $category->name ) .'</a></li>';    
                }
            $output.= '</ul>';
            echo $output;
        }
    
    }
    
    add_shortcode( 'show_category', 'show_category' );