wordpress获取相关文章的函数

wordpress获取相关文章的函数

Number of View: 52

在文章页面,提供文章的ID即可获得此文章的相关文章,相关文章的原理主要是根据Tag相同来提取的,代码如下:请根据实际情况进行更改

function srelated_posts($before_title="",$after_title="",$postID) {   
    global $wpdb, $table_prefix;
   
    $now = current_time('mysql', 1);
    $tags = wp_get_post_tags($postID);  
    $taglist = "'" . $tags[0]->term_id. "'";    

    $tagcount = count($tags);
    if ($tagcount > 1) {
        for ($i = 1; $i < $tagcount; $i++) {
            $taglist = $taglist . ", '" . $tags[$i]->term_id . "'";
        }
    }    
    $limitclause = "LIMIT 5";  
    $q = "SELECT p.ID, p.post_title, p.post_content,p.post_excerpt, p.post_date,  p.comment_count, count(t_r.object_id) as cnt FROM $wpdb->term_taxonomy t_t, $wpdb->term_relationships t_r, $wpdb->posts p WHERE t_t.taxonomy ='post_tag' AND t_t.term_taxonomy_id = t_r.term_taxonomy_id AND t_r.object_id  = p.ID AND (t_t.term_id IN ($taglist)) AND p.ID != $postID AND p.post_status = 'publish' AND p.post_date_gmt < '$now' GROUP BY t_r.object_id ORDER BY cnt DESC, p.post_date_gmt DESC $limitclause;";    
    $related_posts = $wpdb->get_results($q);
    foreach ($related_posts as $related_post ){
        $output .=  '<li><a href="'.get_permalink($related_post->ID).'" title="'.wptexturize($related_post->post_title).'">'.wptexturize($related_post->post_title).'</a></li>';            

    }    
    $output = '<ul class="related_post">' . $output . '</ul>'; 
    return $output;
}
posted @ 2012-09-27 17:20  hust_zk  阅读(1028)  评论(0编辑  收藏  举报