無需插件手工PHP代碼實現(xiàn)WordPress相關(guān)文章調(diào)用

麥子 定制開發(fā)150字?jǐn)?shù) 1591閱讀5分18秒閱讀模式

最近麥子在改造WordPress的官方默認(rèn)主題,實際上官方默認(rèn)主題還是很輕便的,但是有些功能不夠完美,只能通過代碼修改。比如文章沒有相關(guān)文章調(diào)用,這里可以用插件,但是我還是喜歡代碼改進(jìn)反正是自己用的。這里可以用PHP代碼調(diào)用WordPress相關(guān)文章。

//PHP調(diào)用相關(guān)文章 http://bjj.org.cn/wp-relatedposts.html
<div class="related_posts">
<h3>您可能也喜歡這幾篇文章:</h3>
<ul>
<?php
$post_num = 10;
$exclude_id = $post->ID;
$posttags = get_the_tags(); $i = 0;
if ( $posttags ) {
$tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ',';
$args = array(
'post_status' => 'publish',
'tag__in' => explode(',', $tags),
'post__not_in' => explode(',', $exclude_id),
'caller_get_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num,
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<li><a rel="bookmark" href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php
$exclude_id .= ',' . $post->ID; $i ++;
} wp_reset_query();
}
if ( $i < $post_num ) {
$cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ',';
$args = array(
'category__in' => explode(',', $cats),
'post__not_in' => explode(',', $exclude_id),
'caller_get_posts' => 1,
'orderby' => 'comment_date',
'posts_per_page' => $post_num - $i
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<li><a rel="bookmark" href="<?php%20the_permalink();%20?>" title="<?php the_title(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php $i++;
} wp_reset_query();
}
if ( $i == 0 ) echo '<li>沒有相關(guān)文章!</li>';
?>
</ul>
</div>

代碼加入到我們需要的 single.php 對應(yīng)位置,部分代碼自己修改,比如調(diào)用的條數(shù)默認(rèn)是10條。

.related_posts {
margin-top: 5px;
padding-bottom: 10px;
border-bottom: 1px solid #ededed;
}
.related_posts h3 {
margin-bottom: 5px;
}
.related_posts li {
margin-left: 20px;
color: #ccc;
list-style: square;
font-size: 14px;
line-height: 26px;
padding: 0 0 0 5px
}

同時手工調(diào)整CSS樣式。

投上你的一票
 
  • 本文由 麥子 發(fā)表于 2024年12月31日 17:18:10
  • 轉(zhuǎn)載請務(wù)必保留本文鏈接:http://bjj.org.cn/wp-relatedposts.html