• I’ve added a new post_type in my WordPress installation and I would like to query that posts and use them in a loop. The thing is that I have to manually build the arguments depending if it is a category page, or a tag page, etc.

    Is there a way to reuse the already available global WP_Query object, modify the parameter post_type and run the query?

    This is what I want to avoid:

    
    $query = array(
      'post_type' => 'vehicle',
    );
    
    if( is_category() ){
      $query['category_name'] = get_query_var('category_name')
    }
    
    if( is_category() ){
      $query['category_name'] = get_query_var('category_name')
    }
    
    if( is_tag() ){
      $query['tag'] = get_query_var('tag')
    }
    
    // ... and so on
    
    $loop = new WP_Query($query);
    

    I don’t want to use the pre_get_posts method because doing so will alter the global query, which is used for the rest of the website.

Viewing 1 replies (of 1 total)
  • Thread Starter alexandrubau

    (@alexandrubau)

    I’ve fixed it like so, but I don’t think it’s a good approach.

    $query = $wp_query->query_vars;
    
    $query['post_type'] = 'vehicle';
    
    $loop = new WP_Query($query);
    I don't know if it is the right approach but it works for me.

    Let me know, what do you think.

Viewing 1 replies (of 1 total)
  • The topic ‘How to clone the global WP_Query object and change only one parameter?’ is closed to new replies.