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

王朝学院·作者佚名  2016-04-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

通常我们的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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航