WordPress如何在文章正文中插入相关文章
在Wordpress文章页面插入相关文章,非常的简单,但是如何才能在WordPress文章正文中插入相关文章呢?
Arsie Organo的这篇文章提供了一个简便的方法。本文在这篇文章的基础上对代码进行了适当的修改和注释。
Step 1:打开WordPress主题中的single.php
在single.php中找到这行代码:
- <?php the_content(); ?>
Step 2:用下面的这段代码替换Step 1中的代码
- <?php
- $paragraphAfter= 3; //设置在第几个段落之后插入相关文章
- $content = apply_filters('the_content', get_the_content());
- $content = explode("</p>", $content);
- for ($i = 0; $i <count($content); $i++) {
- if ($i == $paragraphAfter) { ?>
- <?php
- //在这个循环中,默认加载当前文章分类下的前5篇最新文章。
- $categories = get_the_category($post->ID);
- if ($categories) {
- echo '<span>或许你会喜欢下面的这些文章:^_^</span>';
- echo '<ul class="post_list">';
- $category_ids = array();
- foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
- $args=array(
- 'category__in' => $category_ids,
- 'post__not_in' => array($post->ID),
- 'showposts'=>3, // 显示相关文章的数量
- 'caller_get_posts'=>1
- );
- $my_query = new WP_Query($args);
- if( $my_query->have_posts() ) {
- while ($my_query->have_posts()) : $my_query->the_post(); ?>
- <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
- <?php
- endwhile;
- }
- wp_reset_query();
- echo '</ul>';
- }
- ?>
- <?php
- }
- echo $content[$i] . "</p>";
- } ?>
Step 3:适当的美化一下
这个需要结合自己使用的主题来进行,我就帮不上忙了。
Pingback: WordPress如何在特定文章中插入某个分类下的全部文章 ¦ Wper.So