If the attachment is attached to a post, the post is determined as “post_parent”.
So, if you are in the attachement template (attachment.php, image.php, etc):
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() );
}
You can get the parent id also with this method, but I just prefer the other:
while ( have_posts() ) {
the_post();
global $post;
$parent_id = $post->post_parent;
}
Once you have the parent post ID, you can get the link, custom fields or whatever you want of the parent post:
if( $parent_id ) {
// parent post has been found, get its permalink
$parent_url = get_permalink( $parent_id );
?>
<a href="https://wordpress.stackexchange.com/questions/217675/<?php echo $parent_url; ?>">
<?php _e('Go to parent post', 'textdomain'); ?>
<a/>
<?php
echo get_post_meta( $parent_id, 'custom-field', true );
}