How can I safely link my WordPress custom recent posts widget title to the category chosen in the widget?

Ive created a widget that shows the most recent posts from a category. I would like to link the widget title to the category archive chosen in the options. Im using wp_dropdown_categories to set the option. This returns the category ID which is works great in setting the query. But, the widget title comes before the loop, so using the ID there is not going to take permalinks into consideration and would be more like a hardcoded <a href="/cat-ID kind thing. Im wondering if there is a better way.

My current code:

This was the solution

$cat_id= $instance['cat'];
$cat_link = get_category_link( $cat_id );
$cat_link_title = '<a href="'.$cat_link.'">'.$title.'</a>';       
if ( $title ) echo $before_title . $cat_link_title . $after_title;`


Since you are saving the category id, you can use get_category_link()

$category_link = get_category_link( $category_id );
if( $category_link )
    $widget_title = '<a href="' . $category_link . '">' . $widget_title . '</a>';
Posted on by aaronwaggs