Home » Wordpress » How to output wp_list_categories with extra markup

How to output wp_list_categories with extra markup

Posted by: admin February 26, 2018 Leave a comment

Questions:

I’m currently using the below script to output all my wordpress categories in an unordered list. How can I have the output with extra markup?

<ul><?php wp_list_categories('title_li&show_count=1');?></ul>

For example:

<ul>
<li>Category 1 &rsaquo;</li> 
<li>Category 2 &rsaquo;</li> 
</ul>

Instead of

<ul>
<li>Category 1</li> 
<li>Category 2</li> 
</ul>

Edit: Changed it to the following with the help of Obmerk Kronen:

$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'number' => 20, // how many categories
  );
$categories = get_categories($args);
  foreach($categories as $category) { 
    echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>&rsaquo;</li>';
    } 
Answers:

There are two ways you can easily do it .

1 – Use get_categories()

$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'number' => 20 // how many categories
  );
$categories = get_categories($args);
  foreach($categories as $category) { 
    echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></li>&rsaquo;';
    } 

2 – use the css :after selector with the same code as you have posted in your question

.my_class li:after{ content:" \203A";}

See other characters and how to use them here