WordPress教程:相關(guān)文章中去除當(dāng)前文章ID方法

字號(hào):


    通常我們的wordpress都是調(diào)用全站的相關(guān)文章,當(dāng)然也會(huì)包括當(dāng)前文章,如何才能調(diào)用相關(guān)文章的時(shí)候去除當(dāng)前文章呢?方法并不難,在調(diào)用函數(shù)里添加一句 post__not_in 即可實(shí)現(xiàn),這個(gè)函數(shù)不要做太多解釋,按字面就可以理解了。
    具體實(shí)施方法如下:
    <?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), //去除當(dāng)前文章ID
    ‘showposts’ =>10,
    ‘caller_get_posts’=>1
    );
    $my_query = new WP_Query($args); ?>
    <div>
    <div>相關(guān)文章</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>隨機(jī)文章</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() ,這個(gè)是重置函數(shù),不多做解釋,可以用也可以不用。