Related posts for a post

时间:2012-03-28 作者:porton

对于一篇帖子,我们需要维护一个“相关帖子”列表(指向其他帖子的链接),这个列表应该对用户可见。

最简单的方法是什么?

1 个回复
SO网友:Tara

或者,您可以将此代码放置在活动主题的函数中。php:

<?php 
// First, backup the default $postdata 
$backup = $post; 
// Now, override the default 
$tags = wp_get_post_tags($post->ID); 
// Now, open the if ( $tags ) statement 
if ($tags) { 
    $tag_ids = array(); 
    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;  
    // Now, setup your custom query args                     
    $args=array( 
        \'tag__in\' => $tag_ids, 
        \'post__not_in\' => array($post->ID), 
        \'showposts\'=>10, // Number of related posts that will be shown.                                                                                                             
        \'ignore_sticky_posts\'=>1 
    ); 
    // Now, perform your custom query 
    $my_query = new wp_query($args);  
    // Next, open your custom query IF statement 
    if( $my_query->have_posts() ) { 
        // We have posts, so let\'s output the opening-containing markup 
        ?> 
        <div class="relatedposts">
        <h3>RELATED:</h3> 

                <?php  
                // Now, open your custom query WHILE statement 
                while ($my_query->have_posts()) {                                                                
                    $my_query->the_post(); 
                    ?>                   
    <ul><li>      <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li></ul>
                     <?php 
                    // Now, close the while $my_query->have_posts() statement 
                } 
                // Now, output your closing-containing HTML content 
                ?>                
</div>          
        <?php 
    // Now, close the if $my_query->have_posts() statement 
    // and open the ELSE statement, for your no-posts content 
    } else { 
        ?> 
        <?php // If there are no related posts ?>
        <p class="noposts">FURTHER READING: <span>You may find more posts like this by searching the site...</span></p>
        <?php 
    // Now, close the ELSE statement 
    } 
// Now, close the if ( $tags ) statement 
} 
// Now, reset the default query 
$post = $backup; 
wp_reset_query(); 
?>

结束