当前位置: 返回首页  //  WordPress如何在文章正文中插入相关文章

WordPress如何在文章正文中插入相关文章

2012年09月13日    ⁄ 作者:呆呆 WordPress开发 ⁄ 共 1537字     评论数 1 ⁄ 被围观 369+ QR:WordPress如何在文章正文中插入相关文章

在Wordpress文章页面插入相关文章,非常的简单,但是如何才能在WordPress文章正文中插入相关文章呢?

 Arsie Organo的这篇文章提供了一个简便的方法。本文在这篇文章的基础上对代码进行了适当的修改和注释。

Step 1:打开WordPress主题中的single.php

在single.php中找到这行代码:

  1. <?php the_content(); ?>  

Step 2:用下面的这段代码替换Step 1中的代码

  1. <?php   
  2.     $paragraphAfter= 3; //设置在第几个段落之后插入相关文章   
  3.     $content = apply_filters('the_content', get_the_content());   
  4.     $content = explode("</p>"$content);   
  5.     for ($i = 0; $i <count($content); $i++) {   
  6.     if ($i == $paragraphAfter) { ?>   
  7.   
  8.         <?php   
  9.         //在这个循环中,默认加载当前文章分类下的前5篇最新文章。   
  10.         $categories = get_the_category($post->ID);   
  11.         if ($categories) {   
  12.             echo '<span>或许你会喜欢下面的这些文章:^_^</span>';   
  13.             echo '<ul class="post_list">';   
  14.         $category_ids = array();   
  15.         foreach($categories as $individual_category$category_ids[] = $individual_category->term_id;   
  16.         $args=array(   
  17.             'category__in' => $category_ids,   
  18.             'post__not_in' => array($post->ID),   
  19.             'showposts'=>3, // 显示相关文章的数量   
  20.             'caller_get_posts'=>1   
  21.         );   
  22.   
  23.         $my_query = new WP_Query($args);   
  24.         if$my_query->have_posts() ) {   
  25.         while ($my_query->have_posts()) : $my_query->the_post(); ?>   
  26.   
  27.         <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>   
  28.   
  29.         <?php   
  30.         endwhile;   
  31.         }   
  32.         wp_reset_query();   
  33.         echo '</ul>';   
  34.         }   
  35.         ?>   
  36.     <?php   
  37.     }   
  38.     echo $content[$i] . "</p>";   
  39.     } ?>  

Step 3:适当的美化一下

这个需要结合自己使用的主题来进行,我就帮不上忙了。

关键字: , , ,