在包含模板文件时,页面的查询已经运行,并且$post全局变量中有一个WP\\u post对象。下面是$post
:
WP_Post::__set_state(array(
\'ID\' => 3440,
\'post_author\' => \'1\',
\'post_date\' => \'2013-08-19 13:06:04\',
\'post_date_gmt\' => \'2013-08-19 13:06:04\',
\'post_content\' => \'\',
\'post_title\' => \'Models\',
\'post_excerpt\' => \'\',
\'post_status\' => \'publish\',
\'comment_status\' => \'open\',
\'ping_status\' => \'closed\',
\'post_password\' => \'\',
\'post_name\' => \'models\',
\'to_ping\' => \'\',
\'pinged\' => \'\',
\'post_modified\' => \'2013-08-23 14:32:57\',
\'post_modified_gmt\' => \'2013-08-23 14:32:57\',
\'post_content_filtered\' => \'\',
\'post_parent\' => 3442,
\'guid\' => \'http://charlesclarkson.com/?page_id=3440\',
\'menu_order\' => 0,
\'post_type\' => \'page\',
\'post_mime_type\' => \'\',
\'comment_count\' => \'0\',
\'filter\' => \'raw\',
\'format_content\' => NULL,
))
如清单所示,此对象中有一个名为
post_parent
. 要访问它,请使用
$post->post_parent
. 顶级页面的post父级设置为
\'0\'
.
根据ACF docs for the_field()
, 还有第二个参数用于将post id传递给函数。
假设页面模板中的代码没有$post
:
<img src="<?php the_child_or_parent_image_src(); ?>">
<?php
function the_child_or_parent_image_src() {
global $post;
if ( $post->post_parent )
the_field( \'header_image\', $post->post_parent );
the_field( \'header_image\' );
}
?>
(注意:代码没有经过很好的测试。)