WordPress教程:相关文章中去除当前文章ID方法

来源:网络编辑考试    发布时间:2012-05-11    网络编辑考试视频    评论

通常我们的wordpress都是调用全站的相关文章,当然也会包括当前文章,如何才能调用相关文章的时候去除当前文章呢?方法并不难,在调用函数里添加一句 post__not_in 即可实现,这个函数不要做太多解释,按字面就可以理解了。

具体实施方法如下:

<?php
$backup = $post;
$tags = wp_get_post_tags($post->ID);
$tagIDs = array();
if ($tags) {
$tagcount = count($tags);
for ($i = 0; $i < $tagcount; $i++) {
$tagIDs[$i] = $tags[$i]->term_id;
}
$args=array(
‘tag__in’ => $tagIDs,
‘post__not_in’ => array($post->ID), //去除当前文章ID
‘showposts’ =>10,
‘caller_get_posts’=>1
);
$my_query = new WP_Query($args); ?>
<div>
<div>相关文章</div>
<ul>
<?php if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href=”<?php the_permalink() ?>” rel=”bookmark” target=”_self” title=”<?php the_title(); ?>”><?php the_title(); ?></a></li>
<?php endwhile;
} else { ?>
<?php $recent=new WP_Query( “showposts=10&caller_get_posts=1&orderby=rand”); while($recent->have_posts()) : $recent->the_post();?>
<li><a href=”<?php the_permalink() ?>” rel=”bookmark” target=”_self” title=”<?php the_title(); ?>”><?php the_title(); ?></a></li>
<?php endwhile;    ?>
<?php } ?>
</ul>
</div>
<?php } else { ?>
<div>
<div>随机文章</div>
<ul>
<?php $recent=new WP_Query( “showposts=10&caller_get_posts=1&orderby=rand”); while($recent->have_posts()) : $recent->the_post();?>
<li><a href=”<?php the_permalink() ?>” rel=”bookmark” target=”_self” title=”<?php the_title(); ?>”><?php the_title(); ?></a></li>
<?php endwhile;    ?>
</ul>
</div>
<?php } ?>
<?php $post = $backup; wp_reset_query(); ?>

这里我还用到了 wp_reset_query() ,这个是重置函数,不多做解释,可以用也可以不用。

本文地址:http://www.wpued.com/7532.html

视频学习

我考网版权与免责声明

① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;

② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。

最近更新

社区交流

考试问答