wordpress怎么在页面上添加相关的文章?

wordpress怎么在页面上添加相关的文章?,第1张

方法一:标签相关

首先获取文章的所有标签,接着获取这些标签下的 n 篇文章,那么这 n 篇文章就是与该文章相关的文章了。现在可以见到的WordPress相关文章插件都是使用的这个方法。下面是实现的代码:

<ul id="tags_related">

<?php

global $post

$post_tags = wp_get_post_tags($post->ID)

if ($post_tags) {

foreach ($post_tags as $tag) {

// 获取标签列表

$tag_list[] .= $tag->term_id

}

// 随机获取标签列表中的一个标签

$post_tag = $tag_list[ mt_rand(0, count($tag_list) - 1) ]

// 该方法使用 query_posts() 函数来调用相关文章,以下是参数列表

$args = array(

'tag__in' =>array($post_tag),

'category__not_in' =>array(NULL), // 不包括的分类ID

'post__not_in' =>array($post->ID),

'showposts' =>6, // 显示相关文章数量

'caller_get_posts' =>1

)

query_posts($args)

if (have_posts()) {

while (have_posts()) {

the_post()update_post_caches($posts)?>

<li>* <a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title_attribute()?>"><?php the_title()?></a></li>

<?php

}

}

else {

echo '<li>* 暂无相关文章</li>'

}

wp_reset_query()

}

else {

echo '<li>* 暂无相关文章</li>'

}

?>

</ul>

方法二:分类相关

本方法是通过获取该文章的分类id,然后获取该分类下的文章,来达到获取相关文章的目的。

<ul id="cat_related">

<?php

global $post

$cats = wp_get_post_categories($post->ID)

if ($cats) {

$args = array(

'category__in' =>array( $cats[0] ),

'post__not_in' =>array( $post->ID ),

'showposts' =>6,

'caller_get_posts' =>1

)

query_posts($args)

if (have_posts()) {

while (have_posts()) {

the_post()update_post_caches($posts)?>

<li>* <a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title_attribute()?>"><?php the_title()?></a></li>

<?php

}

}

else {

echo '<li>* 暂无相关文章</li>'

}

wp_reset_query()

}

else {

echo '<li>* 暂无相关文章</li>'

}

?>

</ul>

第一步,在你的主题模板文件夹下找到single.php文件,用DW打开,找到<!–<p class=postmetadata alt (可能不是每个主题都是同样的代码,原理就是找到文章内容模板结束的地方);

第二步,在你找到的文章内容模板结束的地方上,加入如下代码:<div

<div<?php previous_post_link(‘« « 上一篇:%link’)?</div

<div class=alignright<?php next_post_link(‘下一篇:%link » » ‘)?</div

</div(我的博客如此,可以修改多种不同的表现形式,不一一列举。)

第三步,写CSS样式,并加入到style.css(默认样式表)。我的CSS代码如下:

.alignleft {

float:left

text-align:left

margin-right:10px}

.alignright {

float:right

text-align:right

margin-left:10px}

.alignleft a{

color:#D52300

font-size:12px}

.alignright a{

color:#D52300

至此就大功告成了


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/10984628.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-12
下一篇2023-05-12

发表评论

登录后才能评论

评论列表(0条)

    保存