You're almost there.
Have a look at the manual page for single_cat_title()
, you'll see that it takes two parameters. The first is a prefix to use in the return; the second is the important one here - it defines whether you want the category to be echoed out (if true
), or returned (if false
). So all you need to do is swap:
$thecat = single_cat_title( '', true );
to:
$thecat = single_cat_title( '', false );
In your current code, you're just echoing the title, and $thecat
is being set to null
.