WordPress 获取指定页面ID的父页面函数

get_post_ancestors()函数的作用是获取指定页面的父页面 ID,函数会以数组的形式返回指定页面的所有父页面 ID,比如一个三级页面,通过该 WordPress 函数返回的数组包含了二级页面 ID 和一级页面的 ID,其中数组第一个值的 ID 为直系父页面,最后一个值的 ID 为最顶级的父页面。

  1. <?php get_post_ancestors( $post ) ?>

参数说明

$post – 页面 ID 或页面对像

返回值

数组,如果没有父页面,则返回空数组,如果有父页面,则返回所有父页面 ID 数组
1、获取当前页面的父页面 ID

  1. <?php
  2. global $post;
  3. $pageArray = get_post_ancestors($post->ID);
  4. echo $pageArray[0];
  5. ?>

2、获取最高级页面别名作为 body 的样式名

PS:以下示例代码在 twenty eleven 子主题的 header.php 文件

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

3、获取父页面的 Meta 数据

以下代码是获取顶级页面中名称为“body_class”的自定义字段的值作为 body 的样式名

  1. <?php
  2. $class = '';
  3. if( is_page() ) {
  4. global $post;
  5. $parents = get_post_ancestors( $post->ID );
  6. $id = ($parents) ? $parents[count($parents)-1]: $post->ID;
  7. $class = get_post_meta( $id, 'body_class', true );
  8. }
  9. ?>
  10. <body <?php body_class( $class ); ?>>

4、获取顶级页面的特色图像

以下代码是获取顶级页面的特色图像

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

文章標題:WordPress 获取指定页面ID的父页面函数

文章連結:https://www.wuyanshuo.cn/684.html

更新時間:2022年4月3日

1、本站所有資源均不添加推廣檔案或浮水印,壓縮包內若有廣告檔案和浮水印請勿輕易相信。

2、本站資源均為兩層壓縮,第一層7z(尾碼若為wys,請自行修改為7z)有解壓密碼; 第二層zip或cbz,無解壓密碼,可直接使用漫畫類軟件程式查看; 詳情可參攷解壓教程

3、本站大部分內容均收集於網絡! 若內容侵犯到您的權益,請發送郵件至:admin#wysacg.top我們將第一時間處理! 資源所需價格並非資源售賣價格,是收集、整理、編輯詳情以及本站運營的適當補貼,並且本站不提供任何免費技術支援。 所有資源僅限於參攷和學習,版權歸原作者所有!

给TA打赏
共{{data.count}}人
人已打赏
建站教程

WordPress 友情链接个性化调用

2022-4-3 19:58:51

建站教程

WordPress首页主循环中排除置顶文章的代码

2022-4-3 23:11:18

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索