简体   繁体   中英

Wordpress: modifying archive with custom WP_Query

I want to create a custom category (archive) page for a specific set of categories, adding some querystring vars.

So, I have an url like http://example.com/services/restaurants?city=gotham

If I don't modify WP_Query I have a correct list of services/restaurants but I want to add a filter by city, so if I use WP_Query like this then I get all services (not only restaurants), so it's not working as expected.

This is my code:

<?php
$categories = explode("/", get_query_var('category_name'));

$the_query = new WP_Query(array(
                          'post_type' => 'services',
                          'category_and' => $categories,
                          'meta_query' => [['key' => 'city', 'value' => $_GET['city']]]
                        ) 
                      );

while ( $the_query->have_posts() ) : $the_query->the_post();
?>
    <a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a>
<?php
endwhile;

This is showing all services, not only restaurants even $categories is an array with [0] => 'restaurants' .

Note : if I use SAVEQUERIES and print all $wpdb->queries I can see the correct queries are logged, but then, after this queries, other queries for all services are applied.

How can I use WP_Query to get the category marked by url and add my own meta keys?

Thank you.

Just use at top of your archive.php

if( isset( $_GET['city'] && ''!= $_GET['city'] ) {
    $city = $_GET['city'];
    global $query_string;
    $posts = query_posts($query_string."&meta_key=city&meta_value=$city");       
}

It will modify the original query and append it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM