get_query_var() and permalinks

I have a permalink structure that looks like this,

%category%/%postname%

Read More

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?

Related posts

Leave a Reply

2 comments

  1. 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:

    $my_category = get_query_var('cat');
    echo $my_category;
    

    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:

    global $wp_query
    print_r($wp_query);
    
  2. This helped me get my answer, the problem I found was that the object from

    global $wp_query
    

    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.

    $category = get_query_var('category_name');
    $categoryid = array(get_cat_ID( $category ));
    

    this is particularly useful with pre_get_posts