0

Is anyone able to Redirect the following permalink URL for me?

The URL that WordPress is: http://example.com/?attachment_id=411

I would like to redirect it to new structure i do it, The following code not work with me in old URL:

/* 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 );
        exit();
    }
}
add_filter( 'template_redirect', 'redirect_old_attachment' );
/**/
function wpd_attachment_link( $link, $post_id ){
    $post = get_post( $post_id );
    return home_url( '/media/' . $post->post_name );
}
add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );

So we need when open http://example.com/?attachment_id=411 , redirect it to http://example.com/media/post-title

1 Answer 1

0

You can do this in code, htaccess, or go the fastest way to get it done reliably using a redirection plugin.

Here are three redirection plugins vetted by WordPress VIP:

https://vip.wordpress.com/plugins/safe-redirect-manager/

https://vip.wordpress.com/plugins/wpcom-legacy-redirector/

https://vip.wordpress.com/plugins/external-permalinks-redux/

And here's a link to the one I use on sites:

https://wordpress.org/plugins/redirection/

(glance at the number of active installs 400,000+)

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.