Support » Developing with WordPress » Query Posts multiple conditions

  • I have a theme that uses the following code

    $user_bids = query_posts( array(

    ‘post_status’ => array(‘publish’, ‘accept’, ‘unaccept’),

    ‘post_type’ => BID,

    ‘author’ => $current_user->ID,

    I altered the posts so that they contain post meta “duplicated” that is either equal to 1 or 0

    So I’m trying to figure out how to make a query that brings up all posts unless:

    Post meta “duplicated” is equal to 1.

    but I also need an additional condition:

    If that post has status of “accept” include that post anyway even if post meta “duplicated” is equal to 1

Viewing 1 replies (of 1 total)
  • Moderator bcworkz


    Well, first of all, you shouldn’t use query_posts(), there are better alternatives. I understand it is your theme doing this, but if you are going to be overriding the theme code, you should use the best functions available.

    One more formality before answering your question. When you alter your theme’s code, when your theme is updated, you alterations will be lost. To protect your changes from updates you should use Child Themes.

    Of the better alternatives to query_posts(), I cannot recommend the best without more context. Generally speaking, get_posts() is a good alternative. It is essentially a wrapper for a new WP_Query object, so I’d suggest using the WP_Query class directly. However, if you are wanting to alter a default query (instead of creating a secondary one), your best option is to alter the query through the “pre_get_posts” action.

    I believe the query you wish to run is “posts where post meta key ‘duplicated’ = 1 OR post_status = ‘accept'”. (pseudo SQL, get posts with one, the other, or both) It is that OR that is causing difficulty. WP by default logically ANDs query var criteria. What you need to do is go ahead and set up the query vars as you require, despite the AND logic. Then hook the “posts_request” filter, which passes the resulting SQL query string to your callback. Replace the appropriate AND with OR, returning the modified query string. You will then get all the posts correctly matching your criteria.

    It’s not clear if your desired duplicated criteria is = 1 or != 1. Use whichever is correct. It’s not the real issue, the OR is the main issue here.

Viewing 1 replies (of 1 total)
  • The topic ‘Query Posts multiple conditions’ is closed to new replies.