WordPress非插件实现相关文章

WordPress相关文章现在大部分插件都没有这么更新,而且兼容性做的不是很好,这里我提供一个WordPress非插件实现相关文章的方法。

首先,相关文章的规则是什么?我们来看一看条件。

  1. 在文章页输出相关文章
  2. 关联判断用文章的标签来取相关文章
  3. 需要排除文章本身
  4. 相关文章必须大于1篇

必须要满足以上4个条件。OK,不多话,直接上代码。

// 判断是否存在标签
if(has_tag()) {

  // 当前文章页的标签
  $tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );

  // 查询规则
  $args = array(
    // 查询标签,用tag__in,即“或”关系
    'tag__in'         => $tag_ids,
    // 查询数量
    'posts_per_page'  => 5,
    // 排除当前文章
    'post__not_in' => array(  $post->ID ),
    // 文章类型
    'post_type' => 'post',
  );

  // 主循环查询
  $the_query = new WP_Query( $args );

  // 查询结果文章数量
  $found_posts = $the_query -> found_posts;

  // 如果大于或等于1篇文章
  if( $found_posts >= 1) {

    // 构建相关文章html结构
    echo '<div class="related-posts"><h3 class="related-posts-title">相关文章</h3><ul class="related_post wp_rp">';

    // the loop
    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
      <li><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></li>
    <?php endwhile;
    echo '</ul></div>';
  }

  // 重设主循环
  wp_reset_postdata();
}

发表回复

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