0

I have the following terms in my WordPress project and my post may have connected with some of them or sometimes all terms.

  • A
  • B
  • C
  • D
  • E
  • F

My first post (example1) is connected with terms A, B and C and second post (example2) connected with A, D,E and F. I found wp_get_post_terms() will return all connected terms to a post. But is there a way to show all terms, with connected terms in first position, followed by other terms in the same group? Example: In the detail page of post example2, I would like to show terms as a filter as follows,

  • A
  • D
  • E
  • F
  • B
  • C

Here B and C are not connected with example 2 but I would like to display in single post in disabled state.

1 Answer 1

2

You just need to get the term id's of the terms assigned to a post, and then exclude those terms from get_terms()

You can try the following (Just note, the syntax for get_terms() changed in v4.5, I'll be using the new syntax)

$args       = [];
$taxonomy   = 'my_tax';
$post_terms = get_the_terms( get_the_ID(), $taxonomy ); // Use wp_get_post_terms() if you need special ordering
// Only display the post terms and exclude them if there are terms and no WP_Error
if (    $post_terms
     && !is_wp_error( $post_terms )
) {
    $term_ids = [];
    // Display the list of post terms
    foreach ( $post_terms as $term_object ) {
        // Display term data 

        // Build an array of term ids
        $term_ids[] = $term_object->term_id;
    }

    // Set these id's to the exclude parameter
    $args['exclude'] = $term_ids;
}

// Now we can get the list of all term
$args['taxonomy'] = $taxonomy;
$terms            = get_terms( $args );
// Check if we have terms and no WP_Error
if (    $terms
     && !is_wp_error( $terms )
) {
    // Display the terms
    foreach ( $terms as $term ) {
        // Output the terms as needed
    }
}
1
  • Works great with an edit to select exclude terms as below, // Now we can get the list of all term //$args['taxonomy'] = $taxonomy; //$terms = get_terms( $args ); $terms = get_terms($taxonomy,$args); Thank you
    – Aadi
    Jun 13, 2016 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.