Staffan Estberg
Staffan Estberg

Reputation: 7035

WP Query ignores variable for specific category

Ok I'm probably missing something obvious here since it's a really simple thing, but for some reason I can't get this WP Query to work. I want to query posts only from the category page that the user is currently visiting (using get_the_category). Like so -

$category = get_the_category();
$category_id = $category[0]->cat_ID;

$category_items = new WP_Query( array(
    'post_type' => 'post',
    'cat' => $category_id,
    'showposts' => -1,
    'orderby' => 'rand'
    )
);

$category_id gives me the correct ID for the category page, but referring to it inside WP Query makes the query get all my posts regardless of category.

Upvotes: 1

Views: 270

Answers (1)

user850010
user850010

Reputation: 6359

Try this:

$category = get_the_category();
$category_name = $category[0]->cat_name;

$category_items = new WP_Query( array(
    'post_type' => 'post',
    'category_name' => $category_name,
    'showposts' => -1,
    'orderby' => 'rand'
    )
);

Upvotes: 1

Related Questions