WordPress.org

Forums

[resolved] How to query_posts categories AND and OR at the same time ? (4 posts)

  1. c13303
    Member
    Posted 12 months ago #

    Hi !
    Starting from this :
    query_posts( array( 'category__and' => array(1,2), 'posts_per_page' => 2, 'orderby' => 'title', 'order' => 'DESC' ) );

    I'm wondering if I can make a request with query_posts
    getting all posts belonging to
    (category 1 AND 2) OR (category 2 AND 3)
    ?

    Thanks a lot

  2. Jason
    Member
    Posted 12 months ago #

    Someone may correct me, but I don't think that's possible using WP_Query. You could just query for category 1, 2, and 3, then filter through them yourself. But it'd probably just be faster and more efficient to write the query yourself.

  3. bcworkz
    Member
    Posted 12 months ago #

    It's possible with WP_Query by using 'tax_query'. The essential structure, though with crucial required portions omitted, is something like this:

    'tax_query'=> array(
       'relation'=>'OR',
        array(
          'taxonomy'=>'category',
          'terms'=> array( 1, 2 ),
          'operator'=>'AND',
        ),
        array(
          'taxonomy'=>'category',
          'terms'=> array( 2, 3 ),
          'operator'=>'AND',
        ),
    )
  4. c13303
    Member
    Posted 8 months ago #

    Thanks bcworkz actually I did manage to use tax_query with query_posts ! This query returns posts belonging to research "s" and
    (category 1 AND 7220) OR (category 1 AND 9426)

    (took half a day to figure out hope it will help some other fellows)

    My solution (tested):

    $myquery['tax_query'] =
                    array(
                        'relation' => 'OR',
                        array(
                            'taxonomy' => 'category',
                            'terms' => array( 1, 7270 ),
                            'field' => 'id',
                            'operator' => 'AND'
                        ),
                        array(
                            'taxonomy' => 'category',
                            'terms' => array( 1, 9426 ),
                            'field' => 'id',
                            'operator' => 'AND'
                        ),
    
                );
                $myquery['s']=$_GET['s'];
                query_posts($myquery);

Reply

You must log in to post.

About this Topic