the attachment page should have canonical added to the main post

on attachment page (image.php) I currently have (automatically added by All in One Seo Pack):

<link rel="canonical" href="https://example.com/main-post/image-name" />

And I want to change it to point to the post (where this image is attached)

<link rel="canonical" href="https://example.com/main-post" />

You can ignore All in One Seo Pack if that is difficutl to change, and maybe simple provide a way to add the canonical to the main post.

1 Answer 1


Here's an (untested) example where we inject into the header tag on attachment's pages, the canonical link of the attached post:

add_action( 'wp_head', 'wpse_attachment_parent_canonical' );

function wpse_attachment_parent_canonical()
    // Only target attachment's pages
    if( ! is_attachment() )

    $object = get_queried_object();

    // Make sure we're dealing with a WP_Post object
    if ( ! is_a( $object, '\WP_Post' ) )

    // Only target attachments that are attached to posts
    if( 0 == $object->post_parent )

    // Output canonical link
        '<link rel="canonical" href="%s" />' . PHP_EOL,
        esc_url( get_permalink( $object->post_parent ) )

Note that we can't use the get_canonical_url filter here to adjust the canonical url, as it's only applied to objects with publish post status. Attachments have inherit post status.

  • thanks! To override the existing canonical for attachments, I added this to the rel_canonical() function just before the line $id = get_queried_object_id(); in wp-includes/link-template.php code: if(is_attachment()){ $object = get_queried_object(); if ( is_a( $object, '\WP_Post' ) ){ if( 0 != $object->post_parent ){ printf('<link rel="canonical" href="%s" />' . PHP_EOL,esc_url( get_permalink( $object->post_parent ) )); return;}}} Nov 24, 2020 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.