WordPress:获取post_parent标题

Rya*_*yan 10 wordpress parent title

我创建了一个自定义侧边栏来抓取后父级页面:

query_posts("post_type=page&post_parent=6"); 
Run Code Online (Sandbox Code Playgroud)

我想抓住post_parent的标题(即"关于").the_title将无法正常工作,因为它是子页面的标题.

如何输出post_parent标题?

t31*_*1os 29

echo get_the_title( $post->post_parent );
Run Code Online (Sandbox Code Playgroud)

要么

echo get_the_title( X );
Run Code Online (Sandbox Code Playgroud)

其中X是任何有效的帖子/页面ID.

无需为一个属性获取完整的post对象.


Dem*_*tor 10

看起来你已经获得了父帖的ID,所以你可以使用它:

<?php
    $parent_post_id = 6;
    $parent_post = get_post($parent_post_id);
    $parent_post_title = $parent_post->post_title;
    echo $parent_post_title;
?>
Run Code Online (Sandbox Code Playgroud)

(在$ parent_post_id处插入您的父帖子ID)

参考:http://codex.wordpress.org/Function_Reference/get_post


Tho*_*ier 5

这是您需要的干净漂亮的代码:

当有多个父层次结构级别时,也可以保存以供使用。

<?php 

    $current = $post->ID;

    $parent = $post->post_parent;

    $grandparent_get = get_post($parent);

    $grandparent = $grandparent_get->post_parent;

    ?>

    <?php if ($root_parent = get_the_title($grandparent) !== $root_parent = get_the_title($current)) {echo get_the_title($grandparent); }else {echo get_the_title($parent); }?>
Run Code Online (Sandbox Code Playgroud)