On attachment pages, I have a link back to the post/page where the file was uploaded. (This is not displayed for files that were directly added to the Media Library and that's fine.)
For attachments added to posts and pages, the following code generates the link:
$post = get_post( get_the_ID() );
if ( $post->post_parent ) {
echo '<a href="' . get_permalink( $post->post_parent ) . '">' . get_the_title(
$post->post_parent ) . '</a>';
}
However, when I try viewing an attachment that was uploaded to a custom post type, it doesn't work.
If I display a var_dump of $post, I get the following:
object(WP_Post)#398 (24) { ["ID"]=> int(789) ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2015-04-17 13:32:39" ["post_date_gmt"]=> string(19) "2015-04-17 13:32:39" ["post_content"]=> string(0) "" ["post_title"]=> string(5) "image" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "inherit" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(4) "open" ["post_password"]=> string(0) "" ["post_name"]=> string(5) "image" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2015-04-17 13:32:39" ["post_modified_gmt"]=> string(19) "2015-04-17 13:32:39" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(63) "wp-content/uploads/2015/04/image.jpg" ["menu_order"]=> int(0) ["post_type"]=> string(10) "attachment" ["post_mime_type"]=> string(10) "image/jpeg" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" }
The concerning part is ["post_parent"]=> int(0)
implying that files attached to custom posts don't have a parent.
Can anyone confirm this? Or could this be an error with that way I have setup the custom post type?
I have tried both hierarchical and non-hierarchical types, and with and without 'page-attributes' supported.
Thanks in advance for anyone's help,
Adam