Make use of get_queried_object_id()
in your category page. This will return the ID of the category.
This is really useful little function. It will return the the:
-
author ID on an author archive page
-
term ID on a taxonomy, tag and category archive pages
-
post ID on a single post page
-
page ID of a page
EDIT
From your answer, you can simplify your code to something like this
if ( is_category() ) {
$catid = get_queried_object_id();
} elseif ( is_single() ) {
$cats = wp_get_post_terms( get_queried_object_id(), 'category', array( 'fields' => 'ids' ) ); // category object
$catid = $cats[0];
}
The above code is faster and is more reliable 🙂