Wordpress查询帖子以获取具有唯一标记的帖子

时间:2012-06-20 06:29:06

标签: wordpress

我正在尝试编写一个查询帖子,以便返回一个列表中固定的一个列表,其中列出了与该类别相关的任何一个标记。例如:

<?php $arg = array('cat' => '1','showposts' => 10,'offset' => 0); query_posts($arg); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a class="post-link" title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php $posttags = get_the_tags(); $count=0; if ($posttags) { foreach($posttags as $tag) { $tag_link = get_tag_link($tag->term_id); $count++; if ($count == 1) 
{ echo '<a class="tag-link" href="'.get_tag_link($tag->term_id).'">#'.$tag->name.'</a>'; } } } ?> 

主题A中的帖子

Post_Title_1#tag1
Post_Title_2#tag2
Post_Title_3#tag3
Post_Title_4#tag2&lt; - 我不会发布这个帖子,因为已经显示了Tag2。

问题是我只想要显示带有唯一标签的帖子....我该怎么做...请帮助

1 个答案:

答案 0 :(得分:0)

<?php 
$existing_tags = array();

$arg = array('cat' => '1','showposts' => 10,'offset' => 0); query_posts($arg);

if (have_posts()) : while (have_posts()) : the_post(); 

//get tag and checking if it existed already
$posttags = get_the_tags();
$skip_post = false;

if ($posttags) {
    foreach ($posttags as $tag) {
        $tag_id = $tag->term_id; //the tag's id
        if (isset($existing_tags[$tag_id])) {
            $skip_post = true; //skip this post if the tag already exists
        } else { 
            $existing_tags[$tag_id] = true;
            $skip_post = false; //otherwise track it in our array
        }
        break; //stop after parsing the first tag
    }
}

if ($skip_post) {
    break; //skip the post
}
//display the post and tags as usual
?>
<a class="post-link" title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
echo '<a class="tag-link" href="'.get_tag_link($tag->term_id).'">#'.$tag->name.'</a>';
?> 

所以基本上你需要将获取标记的代码移到顶部,如果数组已经存在则检查它。如果是,请转到下一篇文章,否则显示帖子的其余部分。

相关问题