Search code examples
phpwordpressobject

Wordpress - multiple WP Query objects into one?


In Wordpress it's possible to create own WP Querys for the loop. An example is this:

$my_query = new WP_Query(array('post_parent' => 3, 'post_type' => 'page'));

Another example is this:

$my_query = new WP_Query(array('cat' => 1, 'post_type' => 'post'));

I want a loop that presents pages AND posts from the same loop.

Now to my question. Is it possible to combine these two objects into one? If it is, how? I'm NOT interested in creating two different loops.


Solution

  • what you want would translate to a WHERE ... OR ... condition or a UNION in SQL, eg.

    SELECT * FROM posts WHERE (post_parent = 3 AND post_type = 'page') 
      OR (cat = 1 AND post_type = 'post')
    

    or

    SELECT * FROM posts WHERE post_parent = 3 AND post_type = 'page'
      UNION
    SELECT * FROM posts WHERE cat = 1 AND post_type = 'post'
    

    from looking at the source and the way WP constructs SQL from WP_Query(), i don't think this is possible: there is no OR'ing nor UNION of query vars.

    the only thing that comes to my mind is writing a plugin that implements the posts_where filter (applied to the WHERE clause of the query that returns the post array). you could call this plugin with your different WP Querys, and the plugin would get their WHERE parts and could OR them together.

    see also http://codex.wordpress.org/Custom_Queries