Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - Use wp_query in category archive - how to display the appropriate category?

I am using wp_query in a category archive so that I can use the meta_query to ignore posts with certain meta values.

The problem is that since I am using wp_query, it seems to ignore the category that is currently being viewed and displays all the categories.

Is there a way to retrieve the category (perhaps as defined by the url) that the user is viewing and insert it into the wp_query argument array?

I've seen this suggested solution on stack overflow, but there must be a simpler way to do it since when no the default loop is used, wordpress automatically displays the correct category.

The code currently:

$query = array(
'meta_query' => array(
        array(
            'key' => 'Display',
            'value' => 'Yes',
        )
    ),
    'paged'=> $paged
);

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$pageposts = new WP_Query($query);

if ($pageposts):
while ( $pageposts->have_posts() ) : $pageposts->the_post();
like image 476
waffl Avatar asked Oct 20 '25 02:10

waffl


2 Answers

Well, this is the best solution I could come up with on my own (using single_cat_title to set the variable):

$currentCategory = single_cat_title("", false);

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = array(
    'category_name' => $currentCategory,

    'paged'=> $paged,
    'posts_per_page' => '15'
);
$pageposts = new WP_Query($query);
like image 170
waffl Avatar answered Oct 22 '25 04:10

waffl


I realize this is old, but I had the same problem. I used a method similar to what you came up with for my category archive, but I needed to use WP Query for search.php as well, which led me to looking for a solution. The wordpress codex has a way to preserve the original query for search, and it seems to work for a category archive as well:

<?php
global $query_string;

$query_args = explode("&", $query_string);
$search_query = array();

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach

$search = new WP_Query($search_query);
?>

http://codex.wordpress.org/Creating_a_Search_Page#Preserving_Search_Page_Results_and_Pagination

Should be able to just add the arguments you need and be good to go.

like image 42
Mark Avatar answered Oct 22 '25 03:10

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!