CN2.HK 是专业经营国际CN2网络的服务商,为大陆中小企业提供稳定、安全、合规的国际互联网接入服务。

香港云 cn2.hk 香港云 cn2.hk

服务热线:400 888 9543

服务信箱:idc@cn2.hk

WordPress 主题 CoreNext

我们都比较喜欢给文章添加相关文章,那有没有想过给页面也添加相关页面,下面就一起来看看如何实现吧。

首先,我们需要知道,一般文章(post)都是通过 标签 或 分类 来获取相关文章的,但是 页面(page)默认是没有标签和分类的,所以我们需要先给页面也添加分类和标签功能,具体添加方法可以查看 为WordPress页面(page)添加标签和分类功能。

接下来,你就需要给内容有关联的页面归类或者添加标签。假设有这么两个页面“关于我们”和“公司历史”,那么你可以给这两个页面都添加一个相同的标签“关于我们”。

然后在当前主题的 functions.php 添加下面的代码:

/**
* WordPress为页面(page)添加相关页面
* https://www.wpdaxue.com/show-related-pages-in-wordpress.html
*/
function wpdx_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 class="relatedthumb"><a href="https://www.wpdaxue.com/<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail('thumb'); ?></a></div>
<div class="relatedcontent">
<h3><a href="https://www.wpdaxue.com/<?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();
}

上面的代码会查询与当前页面有相同标签的页面,然后显示出来。如果你想要在页面中调用,那你需要编辑当前主题的 page.php 或者 content-page.php文件,然后在需要显示相关页面的地方使用下面的代码进行调用:

<?php if(function_exists(' wpdx_related_pages')) wpdx_related_pages(); ?>

剩下的工作,就是要你自己添加css样式来完善相关页面的显示效果啦。


发表回复

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

在线客服