I wanted create a widget for the sidebar of the theme that i'm working on recently...But I can't find a way to get links of categories.
This is the code of my widget:
<section class="sidebar-categories">
<div class="inner">
<h3><label>categories</label></h3>
<ul>
<?php
$args = array(
'taxonomy' => 'category',
'parent' => 0, // get top level categories
'orderby' => 'name',
'order' => 'ASC',
'number' => 2,
'hierarchical' => 1,
'pad_counts' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ){
echo '<a href=""><li>'. $category->name . '<span>'. $category->count .'</span></li></a>';
}
?>
</ul>
</div><!-- /inner -->
</section><!-- /sidebar-categories -->
Everything is fine...Markup is exacly what I want...But I don't know what to put in <a href="">
to get the links of categories...
ANY HELP WOULD BE APPRECIATED...
Use
echo get_category_link( $category->term_id );
To get the link of the given category term.
Documentation for the function is here: https://codex.wordpress.org/Function_Reference/get_category_link
Try this,
foreach ( $categories as $category ){
$category_link = get_category_link( $category->cat_ID );
echo '<a href="'.esc_url( $category_link ).'"><li>'. $category->name . '<span>'. $category->count .'</span></li></a>';
}
Change your line
echo '<a href=""><li>'. $category->name . '<span>'. $category->count .'</span></li></a>';
..into
$category_id = get_cat_ID( $category->name );
echo '<a href="' . get_category_link( $category_id ) .'"><li>'. $category->name . '<span>'. $category->count .'</span></li></a>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.