1

Right now, and taking from http://codex.wordpress.org/Template_Tags/wp_list_categories we can use the following code to list categories in a wordpress page:

<?php 
    $args = array(
    'show_option_all'    => '',
    'orderby'            => 'name',
    'order'              => 'ASC',
    'style'              => 'list',
    'show_count'         => 0,
    'hide_empty'         => 1,
    'use_desc_for_title' => 1,
    'child_of'           => 0,
    'feed'               => '',
    'feed_type'          => '',
    'feed_image'         => '',
    'exclude'            => '',
    'exclude_tree'       => '',
    'include'            => '',
    'hierarchical'       => 1,
    'title_li'           => __( 'Categories' ),
    'show_option_none'   => __( 'No categories' ),
    'number'             => null,
    'echo'               => 1,
    'depth'              => 0,
    'current_category'   => 0,
    'pad_counts'         => 0,
    'taxonomy'           => 'category',
    'walker'             => null
    );
    wp_list_categories( $args ); 
?>

And change its options as we like. However this will always echo a <li><a>something</a></li> tag. I'd like to change this code, e.g. I want to make the <a> tags outside <li>. How can I achieve something like this?

0
<ul>
<?php
$categories = get_categories();
foreach($categories as $category)
{
?>
<li><a href="<?php echo get_category_link($category->cat_id);?>">$category->name</a></li>
<?php
}

?>
</ul>

Just simply change the content inside the foreach loop to output how ever your desire. If you are doing this in a number of places drop it into a function and echo the function from your functions file.

Drop this into your functions.php

<?php  
  function outputcategories()
    {
?>
       <ul>
        <?php
        $categories = get_categories();
        foreach($categories as $category)
        {
        ?>
        <li><a href="<?php echo get_category_link($category->id);?>">$category->name</a></li>
        <?php
        }

        ?>
        </ul>
<?php
    }

then to use it run the below

<?php echo outputcategories();  ?>
  • That works, except the link. It'll link to the main page. – coldpumpkin Oct 12 '14 at 12:20
  • $category->cat_ID use this instead of $category->id inside get_category_link – TTech IT Solutions Oct 12 '14 at 12:23
  • your welcome, glad you got this resolved – TTech IT Solutions Oct 12 '14 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.