WordPress调用相关文章

Gavin Wu 2020年12月30日 9:12 Wordpress 1,715 Views

wordpress 调用相关文章的调用代码,一般来说分为按分类来调用 ,就是调用同分类下的文章。还有就是按标签,按文章标签来调用相同标签的文章。方法如下:
一、按分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$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 endwhile; else : ?>
<li> 暂无相关文章</li>
<?php endif; wp_reset_query(); } ?>

二、按标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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' => 10, // 显示相关文章数量
'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>';
}
?>

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Top