通常我们会在wordpress主题的文章的底部看到相关wordpress文章推荐功能,在wordpress程序里通常可以分为随机、分类、标签及后台固定推送id等等相关文章的获取设置。是一个十分方面和页面关联,对用户体验和百度搜索引擎来讲都是极佳的方案,那做为一直被用户冷落的页面我们怎么样为他也添加起来相关页面的功能。
其实很简单,上面我提到了文章是通过随机、分类、标签的功能来进行相关页面调用的,那我们是不是可以为页面(page)也添加个标签和分类功能。这样不就解决问题了,没错下面这段代码就完美的实现了这个功能。
放在你当前使用的主题的 functions.php 文件里:
area data-settings="dblclick" readonly >function wa_related_pages() { $orig_post = $post;global $post;$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('post_type' => 'page', //检索页面类型'tag__in' => $tag_ids, //根据标签获取相关页面'post__not_in' => array($post->ID), //排除当前页面'posts_per_page'=>5 //显示5篇);$my_query = new WP_Query( $args );if( $my_query->have_posts() ) {echo '<div id="relatedpages"><h3>相关页面</h3><ul>';while( $my_query->have_posts() ) {$my_query->the_post(); ?><li><div ><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail('thumb'); ?></a></div><div ><h3><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3><?php the_time('M j, Y') ?></div></li><?php }echo '</ul></div>';} else { echo "没有相关页面";}}$post = $orig_post;wp_reset_query(); }area>16171819202122232425262728293031323334353637function wa_related_pages() { $orig_post = $post;global $post;$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('post_type' => 'page',//检索页面类型'tag__in' => $tag_ids, //根据标签获取相关页面'post__not_in' => array($post->ID), //排除当前页面'posts_per_page'=>5//显示5篇);$my_query = new WP_Query( $args );if( $my_query->have_posts() ) {echo '<div id="relatedpages"><h3>相关页面</h3><ul>';while( $my_query->have_posts() ) {$my_query->the_post(); ?><li><div ><a href="<?php the_permal
ink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail('thumb'); ?></a></div><div ><h3><a href="<?php the_permal
ink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3><?php the_time('M j, Y') ?></div></li><?php }echo '</ul></div>';} else { echo "没有相关页面";}}$post = $orig_post;wp_reset_query(); }
上面的代码会查询与当前页面有相同标签的页面,然后显示出来。如果你想要在页面中调用,那你需要编辑当前主题的 page.php 或者 content-page.php文件,然后在需要显示相关页面的地方使用下面的代码进行调用:
area data-settings="dblclick" readonly ><?php if(function_exists(' wa_related_pages')) wa_related_pages(); ?>area>1<?php if(function_exists(' wa_related_pages')) wa_related_pages(); ?>
剩下的工作,就是要你自己添加css样式来完善相关页面的显示效果啦。