Support » Plugins » Hacks » Taxonomy-related posts in single.php

  • Here’s what I’m looking to do:

    1. Grab a taxonomy value from the post
    2. Create a query based on that value
    3. Create a loop based on that query

    Specifically, I’ve got a taxonomy called “client” and I want there to be “Other work for this client” that appears below the post in single.php. This loop will display all other posts that share the same value in the “client” taxonomy.

    I’ve seen multiple threads about creating loops based on a taxonomy query, but they all require you to assign the taxonomy value manually. I need the value to be grabbed from the current post.

    Thanks in advance.

Viewing 15 replies - 1 through 15 (of 17 total)
  • Here’s an example to work from, i’m off to bed but wanted to quickly post this for you.

    EDIT: Slight typo in code below, now fixed.

    // NOTE: You should be able to place this code before or after the regular loop in your single.php file.
    // Get the terms for the first post (should only be one on single post view anyway)
    $_post_terms = wp_get_post_terms( $posts[0]->ID, 'client','ids' );
    // If there's a result (not invalid taxonomy or 0 results)
    if( !is_wp_error( $_post_terms ) && !empty( $_post_terms ) ) :
    // Create new query object
    $_new_query = new WP_Query;
    $_new_query->query( array( 'client' => $_post_terms[0] ) );
    <!-- if query has posts -->
    <?php if( $_new_query->have_posts() ) : ?>
    	<?php while( $_new_query->have_posts()) : $_new_query->the_post(); ?>
    			// Do something which each result
    			// Notice how this is just like a regular loop
    			// HTML for each result goes here
    			// Example. <h3 class="entry-title"><?php the_title(); ?></h3>
    	<?php endwhile; ?>
    <?php endif; ?>
    <!-- end if query posts -->
    <?php endif; ?>
    <!-- end if post had term -->

    Info on the post term function.

    If you need further help i’ll have to come back to you tomorrow (today for me), as i’m just heading off for some sleep, hope that helps though.. 😉

    Thanks a bunch. I haven’t tried it yet, but it makes perfect sense. Thanks!

    It doesn’t seem to be working. A couple questions:

    1. Does it need to be inside or outside the loop? I’ve tried it both ways.
    2. Do I need to use a post rewind function?
    3. I notice you have the taxonomy using plural in one place and singular in another. The taxonomy is ‘clients’ and the singular is ‘client’.

    Oh, another thing that may or may not be important. This is all in a Post Type called ‘work’ and not part of the standard posts.

    If anyone’s curious, I found this, which seems to work perfectly:


    That pretty much does exactly the same as what i posted above, except i didn’t think to exclude the initial post (good idea), and yes there was a typo in my code before, they should obviously both read “client” …

    It was only intended as an example to work from, and would be used outside the loop.

    Don’t need a rewind, you’re not rewinding a query..

    Happy to hear you found what you wanted in any case… 😉

    Hi, I tried both what you posted as well as the link, but I get no results. This is what I’ve got going now using the code:

    function related_mess() {
    		global $wp_query;
    		$exclude = $wp_query->post->ID;
    		$relation = get_the_term_list( $post->ID, 'tag',' ', ', ', '' );
    if(!empty($relation)) { ?>
    	<ul id="related-mess">
    	<?php $rmquery =  new WP_query(array('clipping' => $relation, 'showposts' =>10, 'post__not_in' => array($exclude)));
    	while ( $rmquery->have_posts()) : $rmquery->the_post(); ?>
    	<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    	<?php endwhile;
    	wp_reset_query(); ?>
    <?php	}

    and within the loop in my single.php file I have:
    <?php related_mess(); ?>

    I have a custom post type of ‘clipping’ and a custom taxonomy of ‘tag’. I’m simply trying to retrieve related posts by ‘tag’. Another thing, each post may have more than one tag, not sure if this works with more than one tag…

    I’ve tried interchanging the code in the new Query with both ‘tag’ and ‘clipping’ and they both gave me the same result…

    What am I doing wrong?


    Ok… I think I’ve got a pretty good solution for you, that works very well. This is something I recently coded for a project I’m working on and it works like a charm and works off tags as you’d like (and supports multiple tagging as well as wordpress conditional tagging like tag1+tag2, etc)…

    Step 1 is to create a custom field with a key and a value. Obviously the key will be the same for every post, the value will change based on association.

    I’m using custom meta boxes to define the custom field, but it’s not necessary, unless you want to. You can of course create the appropriate custom field from the post edit page.

    So we have a post “Mark Painterguy” and we want to add a list of all his paintings (for which we’ve created posts as well) in the sidebar on this post.

    On that post I’m going to define a custom field(global_association_tag) as ‘MarkPainterguy’.

    Ok post, define custom global_association_tag as MarkPainterguy

    Now we need a quick function to grab custom field values anywhere on the post’s page. Here that is:

    // Grabs custom field data and displays/true or doesn't display/false
    function get_custom_field($key, $echo = FALSE) {
    	global $post;
    	$custom_field = get_post_meta($post->ID, $key, true);
    	if ($echo == FALSE) return $custom_field;
    	echo $custom_field;

    So in your sidebar theme file, to output the custom key for global_association_tag, call the function:

    <?php get_custom_field('global_association_tag', true); ?>
    //outputs: MarkPainterguy as set in custom field

    Now just for your info you can set this to just grab the data but not output it by changing true to false (or leave out the argument entirely).

    Now you want to set the custom field value to a variable like:

    <?php $globalAssociationTag = get_custom_field('global_association_tag'); ?>

    Now that you have the custom field set as a variable you can use it in a query like this:

    //query all post by association tag(s)
    $the_query = new WP_Query('showposts=99&orderby=desc&tag='.globalAssociationTag);
    //If there are any posts with that tag...
    <?php if ($the_query->have_posts()) {
    // Then do this while there are post...
    while ($the_query->have_posts()) : $the_query->the_post();
    // Some loop code...
    <h2>Paintings from this Artist</h2>
    <h3><a title="<?php the_title(); ?>" href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
    <div class="excerptText">
    <?php my_content_limit('125'); ?>
    // end while statement and reset the loop...
    <?php endwhile; wp_reset_query();
    // If there are no posts...
    <?php } else { ?>
    Do what you want here... either display nothing or like a heading then a message "there are no paintings for this mofo on our site yet..."
    <?php } ?>

    Now of course, for all the paintings your have for Mark Painterguy, add a tag that matches your global association tag. In this case, “MarkPainterguy”.

    The query will pick up all posts with his paintings automatically and display them, or if there are none, do whatever you want.

    Ok, one more bit. I used a function my_content_limit for the excerpt -it just has one argument which is the number of characters. I set it to 125 in the example.

    Here’s the code for the function:

    # My Custom Content Excerpts
    function my_content_limit($max_char, $more_link_text = '', $stripteaser = 0, $more_file = '') {
        $content = get_the_content($more_link_text, $stripteaser, $more_file);
        $content = apply_filters('the_content', $content);
        $content = str_replace(']]>', ']]>', $content);
        $content = strip_tags($content);
       if (strlen($_GET['p']) > 0) {
          echo "";
          echo $content;
          echo " [...]";
       else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) {
            $content = substr($content, 0, $espacio);
            $content = $content;
            echo "";
            echo $content;
            echo " [...]";
       else {
          echo "";
          echo $content;

    If I’ve understood what you need correctly, you should be set with what I’ve given you. Or at least be able to work off it to make it work for you.

    Hope this helps…


    Thanks! But I’ll be honest I’m a little lost by your example. I’m trying to find all posts tagged with the same term from a custom taxonomy, not from a custom field. I would think I would have to use something like :
    get_the_term_list( $post->ID, 'taxonomyname',' ', ', ', '' )

    How can I apply what you have to get a term list rather than a specific custom field?

    Ps.. one small drawback. I’ve found this doesn’t work if the association tag you use has a space in it. You see I used MarkPainterguy as the tag.

    Does anyone have a solution for this? I haven’t really looked into it all that much because it’s not so important for my use, but for an end user being able to use tags that include spaces as the association tag would be ideal.



    So if I understand you correctly, you want to query for all post within a specific custom taxonomy and that has a specific tag… that right?

    Yes, correct. I need to find all posts that have 1 or more tags as the current single.php post, then randomize them, then show only 4.


    Why don’t you just use what I gave you, and just base your associations off of tags, since you’re already doing that.

    There’s no need to query within a specific custom taxonomy if you only assign the association tag to the post you want to display. Maybe, I’m misunderstanding but here’s how I see it…

    You have a post in the “clients” custom taxonomy. Now you want to associate other posts to it and use that association in a query in order to loop and display the associated posts.

    The custom fields function here is to be used as sort of an anchor, and a way to set a variable to use in your query dynamically rather than hard coding it.

    So John Smith is in the “clients” taxonomy. You want to display all works from John Smith in the sidebar. On this post you set the association custom field, which will be pulled, set as a variable, and used in the query.

    It doesn’t matter what custom taxonomy the other posts fall in, because you’re only linking them by tag. You don’t really need to limit them by custom taxonomy.

    So now you would tag all his works (the posts) with the same association tag (an actual tag, not a custom field – the cf is only set on the “anchor” post).

    The custom field would be pulled from the post about John Smith used to query all the posts, and return only ones with a tag matching the association tag.

    I think this accomplishes the same thing, no? I can see your point if your reluctance is having to set the custom field on the anchor post, and would rather be rid of it, but then there is not a way I can see to make the query dynamic (changing with every new anchor post and displaying the relevant items in the loop).

    Let me know if I’m missing something… Also, check out this post by Justin Tadlock:

    Using custom taxonomies to create a movie database


    I hear you, but what I’m trying to say is that I don’t have a custom field, I have a custom tags taxonomy. You’re saying that I should start out by using this:

    function get_custom_field($key, $echo = FALSE) {
    	global $post;
    	$custom_field = get_post_meta($post->ID, $key, true);
    	if ($echo == FALSE) return $custom_field;
    	echo $custom_field;

    But I’m trying to get an array of values, not just one. So this:
    $custom_field = get_post_meta($post->ID, $key, true);
    I would think it should look more like this:
    $custom_tags = get_the_term_list( $post->ID, 'customtags',' ', ', ', '' )

    … so that I could find all posts that have 1 or MORE related tags, not all posts that match the 1 field/term.

    Now, if I’m crazy, and this is exactly what you’re telling me to do and how to do it, I apologize! Thanks for your help.

    Okay.. before I go any further I need to clarify something with you.

    Can you just give me a example case which would be your ideal result (ie. these are the 5 post i have, this is where i’m placing each, and this is how i’m tagging each)…

    Then what your expected result would be from the case. I think I understand what you’re saying, but I want to be sure before I tell you something.


Viewing 15 replies - 1 through 15 (of 17 total)
  • The topic ‘Taxonomy-related posts in single.php’ is closed to new replies.