WordPress.org

Ready to get started?Download WordPress

Forums

WordPress SEO by Yoast
[resolved] Ability to edit Canonical for attachment.php (8 posts)

  1. BSG21
    Member
    Posted 3 years ago #

    We have setup our attachment pages to allow users to easily navigate all the pictures: http://www.mustangevolution.com/mustang-news/boss-302-laguna-seca-underside-shots/attachment/01-2012-boss-302-underside/

    What I want to be able to do is set the Canonical url for all the attachment.php pages to the original article.

    How can I go about doing this?

  2. Joost de Valk
    Member
    Plugin Author

    Posted 3 years ago #

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

  3. BSG21
    Member
    Posted 3 years ago #

    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.

  4. BSG21
    Member
    Posted 3 years ago #

    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');
  5. Joost de Valk
    Member
    Plugin Author

    Posted 3 years ago #

    you need to do return instead of echo

  6. Joost de Valk
    Member
    Plugin Author

    Posted 3 years ago #

    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' );
  7. BSG21
    Member
    Posted 3 years ago #

    Awesome, that works perfectly. Thank you!

  8. Joost de Valk
    Member
    Plugin Author

    Posted 3 years ago #

    Glad it works, resolving topic.

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic