wordpress调用指定相关文章
时间 : 2023-12-08 10:13:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性
最佳答案
要在WordPress中调用指定相关文章,您可以使用以下方法:
1. 使用相关文章插件:WordPress有很多相关文章插件可供选择,如YARPP(Yet Another Related Posts Plugin)、Contextual Related Posts、Related Posts for WordPress等。您可以在WordPress插件目录中搜索并安装适合您的插件。安装并激活插件后,根据插件的说明进行配置。一般来说,您可以选择在文章底部或侧边栏显示相关文章。
2. 手动添加相关文章:如果您不想使用插件或希望更加灵活地控制相关文章的显示方式,您可以通过自定义代码来手动添加相关文章。将以下代码添加到您的模板文件(如single.php)中的适当位置,以显示与当前文章相关的其他文章:
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>5,
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<h3>相关文章</h3>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><br>
<?php
}
}
wp_reset_query();
}
?>
这段代码会根据当前文章的标签来获取其他拥有相同标签的文章,并显示出来。您可以根据需要自定义显示样式。
请注意,以上方法只是其中的两种常用方法,实际上还有其他的方法可以调用相关文章。使用插件可以更加方便快捷,而手动添加代码可以更加灵活地控制相关文章的显示。根据您的具体需求,选择合适的方法即可。
其他答案
要在WordPress中调用指定相关文章,你可以使用`wp_query`函数来查询相关文章。下面是一个示例代码片段,显示如何调用与当前文章相关的三篇文章。
```php
<?php
// 获取当前文章的标签ID数组
$post_tags = wp_get_post_tags($post->ID);
$tag_ids = array();
foreach ($post_tags as $tag) {
$tag_ids[] = $tag->term_id;
}
// 构建WP_Query查询参数
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => 3,
'orderby' => 'rand' // 随机排序
);
// 运行查询并显示结果
$related_query = new WP_Query($args);
if ($related_query->have_posts()) {
echo '<ul>';
while ($related_query->have_posts()) {
$related_query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
} else {
echo '暂时没有相关文章';
}
wp_reset_postdata();
?>
你可以将以上代码放置在你的主题模板文件中(例如single.php)中的合适位置,以显示与当前文章相关的三篇文章链接。请确保先备份好你的主题文件,以防在修改过程中出现问题。
https/SSL证书广告优选IDC>>
推荐主题模板更多>>
推荐文章