通过代码给WordPress添加相关文章

我们可以给Wordpress一篇文章后面添加相关文章。

好处如下:

  1. 增加网站浏览量;
  2. 减少页面跳出率;

打开正在使用的模板文件夹,找到single.php,在适当的位置添加如下代码:

<!-- 相关文章1 start -->
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo '<div class="related-post">';
echo '<h1>相关文章</h1>';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'posts_per_page'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<ul>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
</ul>
<?php
endwhile;
}
wp_reset_query();
echo '</div>';
}
?>
<!-- 相关文章1 end -->

或者使用如下代码

<!-- 相关文章2 start -->
<div class="related-posts">
<h3>相关文章</h3>
<ul class="related_posts">
<?php
$post_num = 8;
$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
        the_permalink(); ?>" title="<?php
        the_title(); ?>" target="_blank" style="color: #00ccff;"><?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
        the_permalink(); ?>"  title="<?php
        the_title(); ?>" target="_blank" style="color: #00ccff;"><?php
        the_title(); ?></a></li>
<?php
        $i++;
    }
    wp_reset_query();
}
if ($i == 0) echo '<li>没有相关文章!</li>';
?>
</ul>
</div>                    
<!-- 相关文章2 end -->

以上两种代码都可以实现调出相关文章的功能,自己选择适合自己的。以上两种代码测试实现的效果如下:

wordpress相关文章
wordpress相关文章

您如果使用Astra主题,您则需要修改single-layout.php文件,而不是single.php文件。

滚动至顶部