网站内容添加( 有没有想过给页面也添加相关页面怎么办?如何实现)
优采云 发布时间: 2021-10-02 08:01网站内容添加(
有没有想过给页面也添加相关页面怎么办?如何实现)
我们都喜欢在文章中添加相关的文章。您有没有想过在页面中添加相关页面?让我们来看看如何实现它。
首先我们要知道,一般文章(post)是通过标签或者分类来获取相关的文章,但是页面(页面)默认没有标签和分类,所以我们需要给页面先添加分类和标注功能。具体的添加方法可以查看WordPress页面的标注和分类功能。
接下来,您需要对与内容相关的页面进行分类或添加标签。假设有两个页面“关于我们”和“公司历史”,那么您可以在两个页面上添加相同的标签“关于我们”。
然后在当前主题的functions.php中加入如下代码:
<p>/**
* 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 '相关页面';
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>