Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

http://codex.wordpress.org/Function_Reference/get_the_tags http://codex.wordpress.org/Class_Reference/WP_Query#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;
share|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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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