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.

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.

- Mestika

  • 1
    You may wish to accept a few more answers, then others may be more willing to help you. But to clarify, you want the link to point back to the page you are currently on, but with #ID appended...? Jan 25, 2012 at 13:17
  • Yes, exactly. I'm also going to need this meta-data for other things, but essentially this is what I need. And I'll accept my answers :-)
    – Mestika
    Jan 25, 2012 at 14:12
  • Hmm, I think I just found my answer which was laying in front of me the whole time. I'm creating an WP_Query where I get all the posts for that taxonomy term. Then I get all the terms. With a var_dump on my $post I can see all the information I need. I consider this to be what I need.
    – Mestika
    Jan 25, 2012 at 14:16
  • 2
    You should post it as an answer and then accept after 24 hours. It clears up the 'unanswered' pile, and means others can quickly see the solution if they have similar question. Jan 25, 2012 at 14:20

1 Answer 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);

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.