• Attachment – Modifying Permalink Rewrites

    Good day! I cannot find any documentation regarding this matter. I would like to modify my attachment permalink. Instead of pointing to domain.com/post_slug/attachment_slug/ to domain.com/attachment/attachment_slug/. Is this possible?

    /* add new rewrite rule */
    function attachment_rewrite( $wp_rewrite ) {
        $rule = array(
            'media/(.+)' => 'index.php?attachment=' . $wp_rewrite->preg_index(1)
        );
    
        $wp_rewrite->rules = $rule + $wp_rewrite->rules;
    }
    add_filter( 'generate_rewrite_rules', 'attachment_rewrite' );
    
    /* redirect standard wordpress attachments urls to new format */
    function redirect_old_attachment() {
        global $wp;
    
        if( !preg_match( '/^media\/(.*)/', $wp->request ) && isset( $wp->query_vars['attachment'] ) ) {
            wp_redirect( site_url( '/media/' . $wp->query_vars['attachment'] ) , 301 );
        }
    }
    add_filter( 'template_redirect', 'redirect_old_attachment' );

    I already have this but the problem is. There are two ways to visit an attachment page.

    Like for example:
    domain.com/this-is-a-post/this-is-an-attachment/ – When you visit this link you will be redirected to the link below. I want this to be disabled and I want it to point to this link rather domain.com/media/this-is-an-attachment/.

    I read this is possible in the hook of attachment_link but I don’t have any idea. To be honest, my knowledge for permalink rewrites is limited. I really need your help guys.

    Thanks and God Bless!

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘Attachment – Modifying Permalink Rewrites’ is closed to new replies.