• Hello,

    I’m trying to create a shortcode to output a formatted list of categories associated with the post the shortcode is called into. The problem i’m having is that its only displaying 1 category and not all of the categories associated with each post.

    //[categories-list]
    function categories_list_func( $atts ){
     $categories = get_the_category();
    
    	 if($categories) {
     	 	foreach($categories as $category) {
        		$output = '<li class="cat-' . $category->cat_ID . '"><a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "Read more posts from : %s" ), $category->name ) ) . '">'.$category->cat_name.'</a></li>';
            }
    		$second_output = trim($output);
          }
    	  $return_string = '<h4>'.__( "Categories :", "my_site").'</h4><div class="overflow"><ul class="post-categories">' . $second_output . '</ul></div>';
    
     return $return_string;
    
    } // END Categories
    add_shortcode( 'categories-list', 'categories_list_func' );

    Does anyone know what i’m doing wrong?

    Thanks,

    Cyril

Viewing 2 replies - 1 through 2 (of 2 total)
  • try to concatenate the category outputs (with .= );

    example:

    $output .= '<li class="cat-' . $category->cat_ID . '"><a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "Read more posts from : %s" ), $category->name ) ) . '">'.$category->cat_name.'</a></li>';

    possibly also add this $output = ''; after if($categories) {

    thank you alchymyth & mr cyril

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Building a shortcode to display categories’ is closed to new replies.