【问题标题】:Wordpress query related post by tagWordpress 按标签查询相关帖子
【发布时间】:2011-09-09 21:38:58
【问题描述】:

我正在尝试使用与当前帖子/页面相同的标签来查询相关帖子,但这也必须在我已经用于生成网格的代码格式内工作。

<?php
$c = 1; //init counter
$bpr = 3; //boxes per row
if(have_posts()) : while (have_posts()) : the_post(); ?>
<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;
?>

我发现了这个: Wordpress Querying Related Posts by tag

这看起来很有希望,但是当我尝试将它集成时......

<?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(); ?>

不幸的是,它什么也没产生。有什么帮助吗?

谢谢!我认为这两个脚本有冲突,我不是 php 高手。

【问题讨论】:

    标签: php wordpress loops tags


    【解决方案1】:

    来自spec for query_posts:

    *您不应使用query_posts() 创建二级列表(例如,页面底部的相关帖子列表,或侧边栏小部件中的链接列表)。相反,您应该创建一个新的 WP_Query 实例或使用 get_posts().*

    试试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>
    <? } ?>
    

    您需要确保$test 实际上是一个有效的标签或一组标签。

    【讨论】:

    • 有没有办法让代码动态找到附加到页面的标签并显示这些标签,所以如果我用 test 标记那个页面,它会找到 test.但是如果我用'test2'标记另一个它会找到test2?只是想知道这是我想做的事情!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多