0

I'm trying to get the tags of a post on the single content page and displaying a list of other articles that share the tags with the post. For example, the user is reading an article with a tag like 'game'; I want to display the titles of other articles that share the tag 'game'. I'm basically trying to make my own "related pages" section.

How would I do this without using a plugin and which PHP file does the code go? I am using wordpress 3.2.1 and a child theme for the Twenty-Eleven theme.

1

Function Reference/get the tags « WordPress Codex

Class Reference/WP Query « WordPress Codex#Tag_Parameters

add some code like this to content-single.php of your child theme of Twenty Eleven:

$tags = array();
$posttags = get_the_tags();
if( $posttags ) :
  foreach( $posttags as $tag ) { $tags[] = $tag->term_id; }

  $related_query = new WP_Query( array('tag__in' => $tags));
  if( $related_query->have_posts() ) : 
    while( $related_query->have_posts() ) : 
    $related_query->the_post();
      /*whatever you want to output; for instance:*/
      echo '<a href="'; the_permalink(); echo '">'; the_title(); echo '</a><br />';
    endwhile; 
  endif;
endif;
| improve this answer | |
  • hey, I added the code after the_content(); in content-single.php, but nothing shows up – user701510 Jan 3 '12 at 5:49
  • does your single post have any tags? – Michael Jan 3 '12 at 10:34
  • Ah, OK. One more question, does 'tag__in' => $tags mean the other articles have to have all the tags that the current article has to match the database query? For example, if the current article has the tags 'video' and 'game', does another article have to have both the tags 'video' and 'game' to show up or does it only have to share at least one tag? – user701510 Jan 3 '12 at 22:53
  • read again: codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters (multiple tag handling) – Michael Jan 4 '12 at 9:00

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.