0

I've seen dozens of similar but not quite the same questions - It seems easy enough to do a wp_query and get a listing of posts in a given CPT, and sort by a given taxonomy term. However, what i can't seem to figure out or find info on is how to sort via the current page's tax term.

To explain further:

I have a CPT of "Proposals" each proposal can be categorized as part of the taxonomy of "Packages" On each proposal page, i want a list of links to the other proposals that share this given page's same tax-term.

eg. Proposal 1, 2 & 3, are in Package A. When i'm on any of these proposals, I should see links to the other two proposals listed.

I'm guessing i'm just one step away but i've been banging my head against this for a day - much thanks in advance.

1
0

You can get the Packages of the current Proposal using wp_get_object_terms() and then pass some/all of those into a WP_Query.

$terms = wp_get_object_terms( $post_id, 'packages', array( 'fields' => 'ids' ) );
$args = array(
    'post_type' => 'proposals',
    'tax_query' => array(
        array(
            'taxonomy' => 'packages',
            'terms' => $terms
        )
    ),
);
$related = new WP_Query( $args );

If the current Proposal has multiple Packages, this will return a list of Proposals in any of those Packages. You can add 'operator' => 'AND' to the WP_Query $args to restrict it to only Proposals in all the same Packages.

5
  • Thanks for this - though so far it's not returning anything. If i remove the arg for tax_query, it'll return the full list of proposals, so i know that is working. However, with the tax_query, its pulling nothing - I'm ran print_r on $terms and it's returned an empty array. So it doesn't look like something is working within wp_get_objects_terms. To give you a bit more information - i'm attempting to run this query on a single-proposal.php page - before the main loop. (which shouldn't matter since i'm running a full wp_query w/ a reset. I'm wondering if $post_id needs to be different?
    – Tanmccuin
    Feb 21 '15 at 15:56
  • Ok replaced $post_id with $post->ID and now i'm returning an array.
    – Tanmccuin
    Feb 21 '15 at 16:03
  • However, wp_query is still returning empty. Something perhaps with the 'terms' => $terms?
    – Tanmccuin
    Feb 21 '15 at 16:10
  • Ok i was actually able to figure it all out via this explaination - wordpress.stackexchange.com/questions/2649/…
    – Tanmccuin
    Feb 21 '15 at 16:20
  • It' seems we might have been leaving out one step - in parsing the terms via get_objects_in_term
    – Tanmccuin
    Feb 21 '15 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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