get_post_ancestors()函数的作用是获取指定页面的父页面 ID,函数会以数组的形式返回指定页面的所有父页面 ID,比如一个三级页面,通过该 WordPress 函数返回的数组包含了二级页面 ID 和一级页面的 ID,其中数组第一个值的 ID 为直系父页面,最后一个值的 ID 为最顶级的父页面。
- <?php get_post_ancestors( $post ) ?>
参数说明
$post – 页面 ID 或页面对像
返回值
数组,如果没有父页面,则返回空数组,如果有父页面,则返回所有父页面 ID 数组
1、获取当前页面的父页面 ID
- <?php
- global $post;
- $pageArray = get_post_ancestors($post->ID);
- echo $pageArray[0];
- ?>
2、获取最高级页面别名作为 body 的样式名
PS:以下示例代码在 twenty eleven 子主题的 header.php 文件
- <?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 的样式名
- <?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、获取顶级页面的特色图像
以下代码是获取顶级页面的特色图像
- <?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’);
- }
- ?>
文章链接:https://www.wuyanshuo.cn/684.html
更新时间:2022年04月03日
本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn我们将第一时间处理! 资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。 所有资源仅限于参考和学习,版权归原作者所有,更多请阅读无言说网络服务协议。