I am creating a gallery site using FooGallery and having the individual images open in the attachment page. I tried a bunch of codes from here to rewrite the attachment urls from ?attachment_id=8184 to /photos/frienly url but they are not working properly.
This code below works but it is not stable. If it works for one image, few hours later it starts redirecting to the homepage.
Any help on fixing this permanently?
add_filter( 'attachment_link', 'wp_attachment_link', 20, 2 );
function wp_attachment_link( $link, $attachment_id ){
$attachment = get_post( $attachment_id );
$attachment_title = $attachment->post_title ;
$attachment_title = str_replace( ' ' , '-' , $attachment_title );
$site_url = get_site_url( $attachment_id );
$link = $site_url . '/photos/' .$attachment_title;
return $link;
}
// Rewrite attachment page link
add_action( 'init', function() {
add_rewrite_rule( 'photos/([A-Za-z0-9-]+)?$', 'index.php?attachment_id=$matches[2]', 'top' );