wp调用相关文章代码

我们在制作wp模板时会用到相关文章,现将实现代码与大家分享一下:
<?php
$post_tags = wp_get_post_tags($post->ID);
if ($post_tags) {
$tag_list = '';
foreach ($post_tags as $tag)
{
// 获取标签列表
$tag_list .= $tag->term_id.',';
}
$tag_list = substr($tag_list, 0, strlen($tag_list)-1);

$related_posts = $wpdb->get_results("
SELECT post_title, ID
FROM {$wpdb->prefix}posts, {$wpdb->prefix}term_relationships, {$wpdb->prefix}term_taxonomy
WHERE {$wpdb->prefix}term_taxonomy.term_taxonomy_id = {$wpdb->prefix}term_relationships.term_taxonomy_id
AND ID = object_id
AND taxonomy = 'post_tag'
AND post_status = 'publish'
AND post_type = 'post'
AND term_id IN (" . $tag_list . ")
AND ID != '" . $post->ID . "'
ORDER BY RAND()
LIMIT 6");
// 以上代码中的 6 为限制只获取6篇相关文章
// 通过修改数字 6,可修改你想要的文章数量

if ( $related_posts ) {
foreach ($related_posts as $related_post) {
?>
<li><a href="<?php echo get_permalink($related_post->ID); ?>" rel="bookmark" title="<?php echo $related_post->post_title; ?>"><?php echo $related_post->post_title; ?></a></li>
<?php } } else { ?>
<li>暂无相关文章</li>
<?php } } ?>

yiguochun

yiguochun(http://blog.0660hf.com/)0660SEO博客是以seo网站优化,Seo学习,sEO知识,SEO网络推广技巧及站长分享经历的媒体博客,为SEO爱好者和广大站长提供一个SEO案例分享和交流的平台,从分享SEO分享交流过程中带来更多的心满意足。

You may also like...

发表评论