wordpress的get_post_ancestors函数:获取指定页面ID的父页面

2018-10-1910:47:14网站建设与开发Comments2,373 views字数 1552阅读模式

get_post_ancestors()函数的作用是获取指定页面的父页面ID,函数会以数组的形式返回指定页面的所有父页面ID,比如一个三级页面,通过该wordpress函数返回的数组包含了二级页面ID和一级页面的ID,其中数组第一个值的ID为直系父页面,最后一个值的ID为最顶级的父页面。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

函数结构

1
<?php get_post_ancestors( $post ) ?>
参数说明

$post – 页面ID或页面对像文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

返回值

数组,如果没有父页面,则返回空数组,如果有父页面,则返回所有父页面ID数组文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

示例

1、获取当前页面的父页面ID
1
2
3
4
5
<?php 
	global $post;
	$pageArray = get_post_ancestors($post->ID);
	echo $pageArray[0];
?>
2、获取最高级页面别名作为body的样式名

PS:以下示例代码在twenty eleven子主题的header.php文件文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</head>
 
<?php
/* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
$class = '';
/* is it a page */
if( is_page() ) { 
	global $post;
        /* Get an array of Ancestors and Parents if they exist */
	$parents = get_post_ancestors( $post->ID );
        /* Get the top Level page->ID count base 1, array base 0 so -1 */ 
	$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
	/* Get the parent and set the $class with the page slug (post_name) */
        $parent = get_post( $id );
	$class = $parent->post_name;
}
?>
 
<body <?php body_class( $class ); ?>>
3、获取父页面的Meta数据

以下代码是获取顶级页面中名称为“body_class”的自定义字段的值作为body的样式名文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

1
2
3
4
5
6
7
8
9
10
11
12
13
</head>
 
<?php
$class = '';
if( is_page() ) {
	global $post;
	$parents = get_post_ancestors( $post->ID );
	$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
	$class = get_post_meta( $id, 'body_class', true );
}
?>
 
<body <?php body_class( $class ); ?>>
4、获取顶级页面的特色图像

以下代码是获取顶级页面的特色图像文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

1
2
3
4
5
6
7
8
9
<?php
global $post;
$parents = get_post_ancestors( $post->ID );
/* Get the ID of the 'top most' Page if not return current page ID */
$id = ($parents) ? $parents[count($parents)-1]: $post->ID;
if(has_post_thumbnail( $id )) {
	get_the_post_thumbnail( $id, 'thumbnail');
}
?>

函数位置:wp-includes/post.php文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

官方文档:https://codex.wordpress.org/Function_Reference/get_post_ancestors文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/6847.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/cms/6847.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定