0

Hello i found this code and I modified a litle, but i have a problem with it.

I want the link of the attachment page to be something like this

[post-permalink]/[gallery]/[postid]   1234/ .. /1253/ 

I tried this, the URL is like I want to be but gives me a 404 error:

function wpd_attachment_link( $link, $post_id ){
    $post = get_post( $post_id );
    return get_permalink() . 'gallery/' . $post->ID ;
}
add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );

How to do that?

1 Answer 1

1

If you change the structure of the permalink, you have to provide the rewrite rules to understand the new structure. Also, you are not building the attachment permalink correctly. The next code is working:

add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );
function wpd_attachment_link( $link, $attachment_id ){

    $attachment = get_post( $attachment_id );

    // Only for attachments actually attached to a parent post
    if( ! empty( $attachment->post_parent ) ) {

        $parent_link = get_permalink( $attachment->post_parent );
        // make the link compatible with permalink settings with or without "/" at the end
        $parent_link = rtrim( $parent_link, "/" );
        $link =  $parent_link . '/gallery/' . $attachment_id;

    }

    return $link;

}


add_action( 'init', function() {

    // Tell WordPress how to handle the new structure
    add_rewrite_rule( '(.+)/gallery/([0-9]{1,})/?$', 'index.php?attachment_id=$matches[2]', 'top' );

} );

Remember to flush the rewrite rules before trying this code (go to permalink settgins page in the backend and click on the sabe button).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.