query_posts() should be avoided?

后端 未结 2 594
时光说笑
时光说笑 2020-11-28 16:56

I am reading that query_posts() should be avoided in favor of wp_query() and pre_get_posts(). I am not confident with messing with the

2条回答
  •  北海茫月
    2020-11-28 17:18

    Creating a new WP_Query() object is always fine.

    $sort= $_GET['sort'];
    
       if($sort == "pricelow"){
         $sort_args = array('meta_key' => 'price', 'orderby' => 'meta_value_num', 'order', 'ASC');
         $new_query = new WP_Query($sort_args);
        }
    
        blah blah blah...
    

    No no no sorry about that. I didn't see the pre_get_posts hook.

    The code in your question is good for hooking queries. As in described in WordPress Plugin API/Action Reference/pre_get_posts:

    pre_get_posts runs before WP_Query has been setup.

    So it hooks the default WP_Query() where you want (in your code, it changes WP_Query on GET request).

    In your template files, use new WP_Query($args).

提交回复
热议问题