WordPress.org

Support

Support » How-To and Troubleshooting » Return one Custom Taxonomy for WP_Query

Return one Custom Taxonomy for WP_Query

  • operapreneur
    Member

    @operapreneur

    Hi.
    I’m looking to run a WP_Query based on the current post’s custom taxonomy. I do not need an array, just one single taxonomy returned (the post will only have one taxonomy related to it).

    I’ve searched and searched for an answer. I’ve used get_terms, get_the_terms, etc. I’ve been doing it via a tax_query and by using the custom tax. I feel like I’ve exhausted my options. I’m a beginner at this stuff. Any help is much appreciated!

    Here are two examples that are not working:

    $args = array (
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'roles',
    			'field' => 'slug',
    			'terms' => $terms = get_terms('roles')
    			)
    		),
    	'showposts' => '10',
    	'orderby' => 'meta_value_num',
    	'meta_key' => 'role_date',
    	'order' => 'DESC'
    	);

    and

    $args = array (
    	'roles' => $terms = get_terms('roles'),
    	'showposts' => '10',
    	'orderby' => 'meta_value_num',
    	'meta_key' => 'role_date',
    	'order' => 'DESC'
    	 );

Viewing 5 replies - 1 through 5 (of 5 total)
  • I think this will work for you:

    $terms = get_the_terms( $post->ID, 'roles' );
    $args = array (
    	'roles' => $terms[0]->slug,
    	'showposts' => '10',
    	'orderby' => 'meta_value_num',
    	'meta_key' => 'role_date',
    	'order' => 'DESC'
    	 );

    You should also test for no terms found or errors as shown in the Codex.

    operapreneur
    Member

    @operapreneur

    Unfortunately, that doesn’t work either vtxyzzy. It’s still not returning the tax slug. I have no idea what we are missing.

    Any other ideas?

    keesiemeijer
    Moderator

    @keesiemeijer

    Try it with this [untested]:

    $terms = get_the_terms( $post->ID, 'roles' );
    $terms = array_values($terms);
    $args = array (
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'roles',
    			'field' => 'slug',
    			'terms' => terms[0]->slug
    			)
    		),
    	'showposts' => '10',
    	'orderby' => 'meta_value_num',
    	'meta_key' => 'role_date',
    	'order' => 'DESC'
    	);

    operapreneur
    Member

    @operapreneur

    Works brilliantly! Thanks!

    The only part that was missing was a ‘$’ in the tax_query array.

    keesiemeijer
    Moderator

    @keesiemeijer

    Ah yes

    'terms' => terms[0]->slug

    needs to be

    'terms' => $terms[0]->slug

    I’m glad you got it resolved 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Return one Custom Taxonomy for WP_Query’ is closed to new replies.