WordPress.org

Support

Support » Themes and Templates » [Resolved] Query two custom posts and two custom taxonomies

[Resolved] Query two custom posts and two custom taxonomies

  • Hi All,

    I am building a website which has multiple custom post types and taxonomies to keep everything organised.

    The website has a carousel which should display posts from two custom post types (client & events). In addition to the post types the query should only display posts which have the tag “favourite” which is present in two custom taxonomies (tagevents & eventtags).

    I am having trouble constructing a query to pull in the correct posts, as it stands I have:

    <?php query_posts( array( 'post_type' => array('client', 'events'), 'tax_query' => array('tagevents' => 'favourite', 'eventtags' => 'favourite' ) ) ); ?>

    This seems to be pulling in posts from the ‘events’ post type only whilst ignoring the “favourite” tag, any ideas?

    Many thanks in advance for your help,

    Lewis.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays) – you can see this in the second example below.

    http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

    Hi CodeBotics,

    Thanks for your reply, that all made perfect sense. Here is what I have now:

    <?php
    query_posts(
    	array(
    		'post_type' => array(
    			'client',
    			'events'
    		),
    		'tax_query' => array(
    		'relation' => 'AND',
    			array(
    				'taxonomy' => 'tagevents',
    				'terms' => 'favourite'
    			),
    			array(
    				'taxonomy' => 'eventtags',
    				'terms' => 'favourite'
    			)
    		)
    	)
    );
    ?>

    I presume I am missing something as no posts are currently being displayed?

    Thanks!

    Hi Everyone,

    After further reading I found my error and now everything is working as intended. I had ‘AND’ as the relationship which means the returned posts must be in both custom post types, instead I needed to use ‘OR’ for the relationship.

    <?php
    query_posts(
    	array(
    		'post_type' => array('client','events'),
    		'posts_per_page' => -1,
    		'tax_query' => array(
    		'relation' => 'OR',
    			array(
    				'taxonomy' => 'tagevents',
    				'field' => 'slug',
    				'terms' => 'favourite'
    			),
    			array(
    				'taxonomy' => 'eventtags',
    				'field' => 'slug',
    				'terms' => 'favourite'
    			)
    		)
    	)
    );
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    ?>

    Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] Query two custom posts and two custom taxonomies’ is closed to new replies.
Skip to toolbar