Viewing 7 replies - 1 through 7 (of 7 total)
  • Plugin Contributor Joost de Valk

    (@joostdevalk)

    Hmm that would require a custom filter at this point, there is a filter called wpseo_canonical that you can use to do that.

    Thread Starter BSG21

    (@bsg21)

    Thanks for the response. How do I get the post url that the attachment is assigned to outside the loop since I will need to do this before the loop.

    Thread Starter BSG21

    (@bsg21)

    Alright, I got it to work but it is outputting the canonical <link > tag twice.

    This is the code I used I just need to know what extra step(s) I need to take to keep it from duplicating

    function attachment_wpseo_canonical ($can) {
     global $wp_query;
     $attachment_page_id = $wp_query->post->ID;
     $parent_post = get_post($attachment_page_id);
     $parent_post_id = $parent_post->post_parent;
    
     $parent_post_permalink = get_permalink($parent_post_id);
     echo "<link rel=\"canonical\" href=\"$parent_post_permalink\" />";
     }
     add_filter('wpseo_canonical','attachment_wpseo_canonical');
    Plugin Contributor Joost de Valk

    (@joostdevalk)

    you need to do return instead of echo

    Plugin Contributor Joost de Valk

    (@joostdevalk)

    oh and btw the code is wrong too, as it would now do this on all pages. It should be:

    function wpseo_attachment_canonical_parent( $canonical ) {
    	if ( is_attachment() ) {
    		global $post;
    		$attachment = get_post( $post->ID );
    		$parent_post_id = $attachment->post_parent;
    		$canonical = get_permalink( $parent_post_id );
    	}
    	return $canonical;
    }
    add_filter( 'wpseo_canonical', 'wpseo_attachment_canonical_parent' );
    Thread Starter BSG21

    (@bsg21)

    Awesome, that works perfectly. Thank you!

    Plugin Contributor Joost de Valk

    (@joostdevalk)

    Glad it works, resolving topic.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Ability to edit Canonical for attachment.php’ is closed to new replies.