WordPress: link image post to parent post

This post explains how to change the linking behavior of image posts for the WordPress default theme twenty eleven.

Problem Overview: WordPress Link on Image points to next Image in Gallery

If you upload a gallery in WordPress and insert it in a post, each of these images will get their own post. In this post, only that image will be displayed (and some meta information) and if a user clicks on it the next image in the gallery will be displayed if you use the WordPress default theme twenty eleven.

And here is the problem: the user does not expect to be taken to the next image in the WordPress gallery. Most likely a user just came from a search engine and wants to read the post that belongs to the image (and you probably want the user to do just that as well).

For example, lets say you create a post called “a test” and add a gallery with the images my-test.png and my-second-test.png.
Now three WordPress posts will be created and are available under the following urls:

http://example.org/blog/2012/a-test                 # the post
http://example.org/blog/2012/a-test/my-test         # the first image
http://example.org/blog/2012/a-test/my-second-test  # the second image
And the image displayed on http://example.org/blog/2012/this-is-a-test/my-test links to http://example.org/blog/2012/this-is-a-test/my-second-test.

Solution: edit image.php file of twenty eleven WordPress Theme

replace the following code that can be found on line 74 of the image.php file:

<a href="<?php echo esc_url( $next_attachment_url ); ?>"
    title="<?php the_title_attribute(); ?>" rel="attachment">
<a href="<?php echo esc_url( get_permalink( $post->post_parent ) ) ?>"
    title="<?php echo esc_attr( strip_tags( get_the_title( $post->post_parent ) ) ) ?>" >
It is best to do this in a child theme so that it is not overwritten when you update WordPress.

Related Posts:

Leave a Reply

Your email address will not be published.