I have a permalink structure that looks like this,
%category%/%postname%
I have a category.php template coded up and and trying to pull of the post of a certain category, so for example my URL may look like this,
/category/category1
I want all posts that are in category1 to be return however, when using the following code I get null returned,
get_query_var('cat')
I assume that this code is looking for URL that looks like this,
?cat=category1
So how do I make it work with permalinks?
WordPress rewrites rules invisibly translate pretty permalinks to the non-pretty format internally, and set the appropriate variables and load the requested page, you don’t need to do anything in your template to load posts from a category on a category page.
The
cat
query var specifically will be set to the ID of the requested category, not the name.That said, this:
should print the selected category ID on a category page. If it’s not, we’d have to see your code to help you further.
Also, have a look at the
$wp_query
global to see all query vars set on a particular page:This helped me get my answer, the problem I found was that the object from
didn’t contain a category id if permalinks were turned on. However it did contain a category name, thus to retrieve the category id the following code worked for me.
this is particularly useful with
pre_get_posts