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() )
return;
$object = get_queried_object();
// Make sure we're dealing with a WP_Post object
if ( ! is_a( $object, '\WP_Post' ) )
return;
// Only target attachments that are attached to posts
if( 0 == $object->post_parent )
return;
// Output canonical link
printf(
'<link rel="canonical" href="https://wordpress.stackexchange.com/questions/271590/%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.