Which post does a taxonomy term belongs to?

I’m having a page which displays all custom taxonomy terms for a particular type which I get from the URL. I use this code to retrieve all the terms:

$args = array(
'post_type' => 'mycustomposttype',
'programtype' => ’my-custom-taxonomy-term
);
$programtype = new WP_Query($args);
while ( $programtype->have_posts() ) : $programtype->the_post();
$terms = get_the_terms( $post->ID, 'my-custom-taxonomy );

This all works perfectly fine but then I want to produce a link, when pressing on each of the terms to redirect back to the original custom post it belongs to.

Read More

Let me give an example:
The custom post type “Programblock” with ID 19, has three custom taxonomy terms attached to it, which is called “events”. The three terms is listed on above mentioned page, but then I want to produce a link which takes them back to the custom post type page “Programblock” with the post ID as hashtag, like this:
http://www.my-domain.com/programblock#19

How can I reverse this so Instead of asking “Which terms does this post has” I want to ask, “Which post does this term belongs to”.

I hope I’ve explained myself clear enough, otherwise please ask.

Sincere
– Mestika

Related posts

Leave a Reply

1 comment

  1. You could do it using the term_link filter.
    Something roughly as follows:

    function my_term_link($termlink, $term, $taxonomy) {
       global $post;
       if ($taxonomy == 'my-custom-taxonomy') {
          return get_permalink( $post->ID ) . '#' . $term->term_id;
       }
    }
    
    while ( $programtype->have_posts() ) : $programtype->the_post();
       $terms = get_the_terms( $post->ID, 'my-custom-taxonomy' );
       add_filter('term_link', 'my_term_link', 10, 3);
       foreach ($terms as $term) {
          $link = get_term_link( $term, 'my-custom-taxonomy' );
          // Use link here
       }
       remove_filter('term_link', 'my_term_link', 10, 3);
    endwhile;