• Resolved Pradeep Singh

    (@psnegi75)


    add_shortcode( ‘my_cat_list’, ‘my_list_categories_shortcode’ );

    /**
    * this function outputs your category list where you
    * use the [my_cat_list] shortcode.
    */

    function my_list_categories_shortcode() {
    global $post;
    $post_id = $post->ID;

    $args = array(
    ‘orderby’ => ‘name’,
    ‘order’ => ‘ASC’,
    ‘style’ => ‘list’,
    ‘post_type’ => ‘projects’,
    ‘current_category’ => 0,
    ‘title_li’ => __( ‘Categories’ ),
    ‘show_option_none’ => __(‘No categories’),
    ‘taxonomy’ => ‘projects-category’
    );

    return wp_list_categories($args);
    }

    I am trying to get Only checked categories of a single post on detail page. This is showing all categories of CPT. If I supply post id it show nothing.

    Please recommend.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi, psnegi75, although this doesn’t entirely address all of your issues – I’m not entirely sure what you mean by “Only checked categories of a single post on detail page” – , I think this explanation on the developer page should help at least a little bit:

    https://developer.wordpress.org/reference/functions/wp_list_categories/#comment-content-1169

    It’s important to note is that you need to get the term IDs within the post and then include those IDs within the args array, as otherwise it will include all categories.

    Thread Starter Pradeep Singh

    (@psnegi75)

    Thank you @plantprogrammer exact what I was looking to achieve, it is resolved now.

    function my_list_categories_shortcode() {    
    	global $post;	
    	
    	$taxonomy = 'projects-category'	;
     
    	// Get the term IDs assigned to post.
    	$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
     
    	// Separator between links.
    	$separator = ', ';
     
    	if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
    	 
    		$term_ids = implode( ',' , $post_terms );
    	 
    		$terms = wp_list_categories( array(
    			'title_li' => '',
    			'style'    => 'none',
    			'echo'     => false,
    			'taxonomy' => $taxonomy,
    			'include'  => $term_ids
    		) );
    	 
    		$terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );				
    		
    		$catg = explode(',', $terms);	
    				
    		if(!empty($catg)){
    			echo  '<div class="projects-category"><h4>Categories</h4><ul>';					
    			foreach($catg as $cat){ echo  '<li>'.$cat.'</li>'; }		
    			echo  '</ul></div>';
    		}
    			
    	}
    }
    • This reply was modified 3 years, 1 month ago by bcworkz.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get Categories of a custom post type in single page’ is closed to new replies.