WordPress.org

Ready to get started?Download WordPress

Forums

Return one Custom Taxonomy for WP_Query (6 posts)

  1. operapreneur
    Member
    Posted 1 year ago #

    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'
    	 );
  2. vtxyzzy
    Member
    Posted 1 year ago #

    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.

  3. operapreneur
    Member
    Posted 1 year ago #

    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?

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    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'
    	);
  5. operapreneur
    Member
    Posted 1 year ago #

    Works brilliantly! Thanks!

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

  6. keesiemeijer
    moderator
    Posted 1 year ago #

    Ah yes

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

    needs to be

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

    I'm glad you got it resolved :-)

Topic Closed

This topic has been closed to new replies.

About this Topic