用WordPress简码(shortcode)在文章中显示相关日志

上次介绍了各种相关文章的显示方法,那些方法都是在文章后或者侧边栏等显示相关文章,有没有方法在文章中显示相关文章呢?应用wordpress简码可以实现。

方法很简单,在functions.php中加入以下代码:

function related_posts_shortcode( $atts ) {

extract(shortcode_atts(array(

‘limit’ => ‘5’,

), $atts));

global $wpdb, $post, $table_prefix;

if ($post->ID) {

$retval = ‘<ul>';

// Get tags

$tags = wp_get_post_tags($post->ID);

$tagsarray = array();

foreach ($tags as $tag) {

$tagsarray[] = $tag->term_id;

}

$tagslist = implode(‘,’, $tagsarray);

// Do the query

$q = “SELECT p.*, count(tr.object_id) as count

FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy =’post_tag’ AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID

AND p.post_status = ‘publish’

AND p.post_date_gmt < NOW()

GROUP BY tr.object_id

ORDER BY count DESC, p.post_date_gmt DESC

LIMIT $limit;”;

$related = $wpdb->get_results($q);

if ( $related ) {

foreach($related as $r) {

$retval .= ‘

<li><a title=”‘.wptexturize($r->post_title).'” href=”‘.get_permalink($r->ID).'”>’.wptexturize($r->post_title).'</a></li>

‘;

}

} else {

$retval .= ‘

<li>No related posts found</li>

‘;

}

$retval .= ‘</ul>

‘;

return $retval;

}

return;

}

add_shortcode(‘related_posts’, ‘related_posts_shortcode’);

然后在希望显示相关日志的位置加上:

[related_posts]

大功告成!

实际效果请参看:http://opeza.com/love/148.html  文章中第二段下面的相关文章

wordpress


标签:  |  | 
将此文分享到:


转载请注明来自风腾网-wordpress企业主题,本文地址:http://fengten.com/614.html
除非注明,风腾网-wordpress企业主题文章均为原创,转载请注明出处和链接!
友荐云推荐

相关文章

6 条评论

*

*

顶部 友荐云推荐