WordPress.org

Support

Support » Plugins and Hacks » [Resolved] Ability to edit Canonical for attachment.php

[Resolved] Ability to edit Canonical for attachment.php

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

    @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.

    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.

    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 Author Joost de Valk
    Member

    @joostdevalk

    you need to do return instead of echo

    Plugin Author Joost de Valk
    Member

    @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' );

    Awesome, that works perfectly. Thank you!

    Plugin Author Joost de Valk
    Member

    @joostdevalk

    Glad it works, resolving topic.

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