All attachments has got a post parent which you can access with $post->post_parent
inside the loop or get_queried_object()->post_parent
outside the loop on your image.php
or similar single post pages. (See my question here and the answer by @gmazzap why you should rather avoid $post
outside the loop)
Now that you have the post parent ID, it is easy to rewrite your function: (CAVEAT: Untested)
function get_parent_post_anchor()
{
/*
* Make sure we are on an attachment page, else bail and return false
*/
if ( !is_attachment() )
return false;
/*
* Get current attachment object
*/
$current_attachment = get_queried_object();
/*
* Get the permalink of the parent
*/
$permalink = get_permalink( $current_attachment->post_parent );
/*
* Get the parent title
*/
$parent_title = get_post( $current_attachment->post_parent )->post_title;
/*
* Build the link
*/
$link = '<a href="' . $permalink . '" title="' . $parent_title . '">' . $parent_title . '</a>';
return $link;
}
You can then use it as follow
echo get_parent_post_anchor();