WordPress.org

Forums

[resolved] Query two custom posts and two custom taxonomies (4 posts)

  1. lewismalpas
    Member
    Posted 2 years ago #

    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.

  2. CodeBotics
    Member
    Posted 2 years ago #

    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

  3. lewismalpas
    Member
    Posted 2 years ago #

    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!

  4. lewismalpas
    Member
    Posted 2 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic