• Resolved mastrup

    (@mastrup)


    I have created a taxonomy (slug: customcategory) and attached it to my custom post type.

    My taxonomy is set to allow parent-child relationships.
    This is an example of the hierarchy:

    1. CFO Services
    1. Processes
    1. Procure to Pay processes
    2. Order to Cash
    3. Treasury & Cash Management

    I have then created a post and chosen the “Order to Cash” taxonomy as its category.
    On my taxonomy page I want to show all the posts associated with the current taxonomy.
    I am doing that with the following code:

    $posts_array = get_posts(
    	array(
    		'posts_per_page' => -1,
    		'post_type' => 'customdocument',
    		'tax_query' => array(
    			array(
    				'taxonomy' => 'customcategory',
    				'field' => 'term_id',
    				'terms' => array( $id ),
    			)
    		)
    	)
    );
    foreach ($posts_array as $item) {
    	echo $item->post_title;
    }

    When I access my taxonomy page (url: /customcategory/cfo-services/processes/order-to-cash) the code above returns all posts associated to this taxonomy – As it should.
    But when I access one of the parent taxonomies (for example: /customcategory/cfo-services/) it returns all the posts associated with the child taxonomies.
    My goal is to show only the posts where the current taxonomy is chosen.

    How can I achieve this?

    • This topic was modified 8 years, 8 months ago by mastrup.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Contributor Michael Beckwith

    (@tw2113)

    The BenchPresser

    I have to wager it’s, at least in part, because all of the child terms would also be having the parent term as well, thus why they’re included.

    I’d look over https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters. The first thing that stuck out to me was the “include_children” parameter. Worth trying out.

    Thread Starter mastrup

    (@mastrup)

    Thank you for pointing that out to me, Michael! 🙂

    This solved my problem:

    
    $args = array(
    	'post_type' => 'customdocument',
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'customcategory',
    			'field'    => 'slug',
    			'terms'    => 'customCategorySlug',
    			'include_children'	=> 0
    		),
    	),
    );
    $query = new WP_Query( $args );
    
    Plugin Contributor Michael Beckwith

    (@tw2113)

    The BenchPresser

    Welcome. 😀

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Only show posts with the current taxonomy chosen’ is closed to new replies.