如何在WordPress中获取当前页面的父页面ID和标题?

7

这是我的代码,但它无法工作。

global $post;
echo get_the_title( wp_get_post_parent_id( $post->post->ID ) );

但是这并没有起作用。 提前谢谢你。

WordPress的哪个版本?你在哪里执行这段代码? - Leszek P
最新版本,在 header.php 文件中。 - Therichpost
转储此变量:$parent = get_post($post->post_parent); - Leszek P
没听懂你的意思。 - Therichpost
5个回答

7

对于父页面ID

$post->post_parent;

获取当前页面标题

$post->post_title;

尝试使用 $wp_query->post->post_title; - Ritz Cool

6

对于父页面ID

<?php
  echo wp_get_post_parent_id(get_the_ID());
?>    

我们甚至不需要提供 get_the_ID() 函数,因为该函数默认使用 null 值,并检索存储当前文章 ID 的全局文章变量。 - Deele

2
在古腾堡中:
wp.data.select('core/editor').getEditedPostAttribute('parent')

希望对某人有所帮助


1
如果您想创建一个链接到帖子的父级,请使用以下代码:
<a href="<?= get_permalink($post->post_parent) ?>">
  <?= get_the_title($post->post_parent) ?>
</a>
&rarr; <?= the_title() ?>

这将导致以下结果,即:

最新新闻 → 一些新闻标题


0
对于Astra主题和页面模板look.php,我做了以下操作: $post->post_parent; 不起作用,因为在我的情况下该函数不在循环中。我通过functions.php运行它。将$post->post_parent插入页面模板时可以正常工作,但在编辑主题函数时却不行 ;)
function add_script_before_header() {

  $current = $post->ID;
  $parent = $post->post_parent;
  $grandparent_get = get_post($parent);
  $grandparent = $grandparent_get->post_parent;

  if ($root_parent = get_the_title($grandparent) !== $root_parent = get_the_title($current)) {
    echo get_the_title($grandparent); 
  }

  $after = $parent;
  if ( is_page_template( 'look.php' ) ) {
            echo $after . ' - ';
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接