• Hi I am working on a new WordPress site where there is a Nature section which shows photos of various nature elements.

    There are loads of posts, each depicting a picture of something, eg a moth, a butterfly, a tree, a wasp etc.

    So the way I have set this up is to create a custom post type of “Nature Post”. Then set up several custom taxonomies – Group, Order, Family, Species amongst others.

    So I might have the following –

    Group Order Family
    —– —– ——
    Insect Lepidoptera NOCTUIDAE
    Insect Lepidoptera CRAMBIDAE
    Bird Galliformes PHASIANIDAE
    Bird Passeriformes SITTIDAE

    So on each post I display each of the custom taxonomy values as a hyperlink so you can see all of Lepidoptera for example.

    What I want to be able to though is to be able to sort the display of posts a number of different ways – so for example I would like to be able to display a page of Lepidoptera, sorted by Family. So in essence take the posts which form a subset of a custom taxonomy, and sort them by the values of another custom taxonomy that applies to the same posts.

    I’d be grateful for any advice here. Thanks in advance.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with a tax_query.
    https://codex.www.ads-software.com/Function_Reference/WP_Query#Taxonomy_Parameters

    Here is an example:

    <?php
    // get all order taxonomy terms
    $order_terms = get_terms( 'order', 'fields=ids' );
    
    // get all posts that have order terms and a family term NOCTUIDAE
    $args = array(
    	'post_type' => 'post', // your post type
    	'tax_query' => array(
    		'relation' => 'AND',
    		array(
    			'taxonomy' => 'order', // taxonomy slug
    			'field' => 'id',
    			'terms' => $order_terms
    		),
    		array(
    			'taxonomy' => 'family', // taxonomy slug
    			'field' => 'slug',
    			'terms' => array( 'noctuidae' ), // term slugs
    		)
    	)
    );
    
    $query = new WP_Query( $args );
    ?>

    https://codex.www.ads-software.com/Function_Reference/WP_Query

    Thread Starter tonysab

    (@tonysab)

    Blimey that looks good, although I don’t think it’s quite what I want. Using my example I want to display posts where the order is Lepidoptera and I want to display them in family sequence, so I would expect to see 2 posts, the one with a family value of CRAMBIDAE first, then followed by the one with NOCTUIDAE.
    Thanks for your help though.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Display custom posts from a custom taxonomy, sorted by another custom taxonomy’ is closed to new replies.