Goal:
From my image.php, I am displaying the attachment image and some descriptions. I also want get the post from where it was originally posted. I only need the title and the url so that you can link back from the original post.

Problem:
It’s not displaying the correct post title and url. Instead, it’s displaying the first and last post I posted. When I change the number to “1” instead of “-1”, the name just change to either the first post or the last post.

Code:
From this post: Find the post an attachment is attached to

<?php
    // Get all image attachments
    $all_images = get_posts( array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    ) );
    // Step through all image attachments
    foreach ( $all_images as $image ) {
        // Get the parent post ID
        $parent_id = $image->post_parent;
        // Get the parent post Title
        $parent_title = get_the_title( $parent_id );
        // Get the parent post permalink
        $parent_permalink = get_permalink( $parent_id );
    }

    echo "This image is posted to: <a href="".$parent_permalink ."" >".$parent_title."</a>";
?>

1 Answer
1

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();

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *