Wordpress query related post by tag
I am trying to query related posts by using the tags the same to the current post/page, but this also had to work within the code format I am already using to generate a grid.
<?php
$c = 1; //init counter
$bpr = 3; //boxes per row
if(have_posts()) : while (have_posts()) : the_pos开发者_如何学JAVAt(); ?>
<div class="postgrid" id="post-<?php the_ID(); ?>">
<div class="postthumb">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('grid-post-image'); ?></a><div class="borderthumb"></div><div class="posttitle"><h1><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>
<p><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">Click for more</a></p></div>
</div>
</div>
<?php
if($c == $bpr) :
?>
<?php
$c = 0;
endif;
?>
<?php
$c++;
endwhile;
endif;
?>
I found this: Wordpress Querying Related Posts by tag
Which seemed promising, but when I tried to integrate it like..
<?php
$c = 1; //init counter
$bpr = 3; //boxes per row
$test = "";
$posttags = get_the_tags();
$test = '';
$sep = '';
if ($posttags) {
foreach($posttags as $tag) {
$test .= $sep . $tag->name;
$sep = ",";
}
}
query_posts('tag=' .$test . '&showposts=-1'); if(have_posts()) : while (have_posts()) : the_post(); ?>
it unfortunately generated nothing. any help?
Thanks! I think the two scripts are conflicting and I'm no php whizz.
From the spec for query_posts
:
*You should not use query_posts()
to create secondary listings (for example, a list of related posts at the bottom of the page, or a list of links in sidebar widget). Instead, you should make a new instance of WP_Query or use get_posts()
.*
Try get_posts()
:
$posts = get_posts('tag=' .$test); foreach($posts as $post){ setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<? } ?>
You'll need to make sure that $test
is actually a valid tag or set of tags.
精彩评论