如果附件附加到帖子,则该帖子将被确定为“post\\u parent”。
因此,如果您在attachement模板中(attachment.php、image.php等):
while ( have_posts() ) {
the_post();
// Get parent id of current post (get_the_ID() gets id of current post,
// whicdh is the attachement, as we are in the attachment template)
$parent_id = wp_get_post_parent_id( get_the_ID() );
}
您也可以使用此方法获取父id,但我更喜欢其他方法:
while ( have_posts() ) {
the_post();
global $post;
$parent_id = $post->post_parent;
}
拥有父帖子ID后,您可以获得父帖子的链接、自定义字段或任何您想要的内容:
if( $parent_id ) {
// parent post has been found, get its permalink
$parent_url = get_permalink( $parent_id );
?>
<a href="<?php echo $parent_url; ?>">
<?php _e(\'Go to parent post\', \'textdomain\'); ?>
<a/>
<?php
echo get_post_meta( $parent_id, \'custom-field\', true );
}