user2334436
user2334436

Reputation: 939

Remove attachment slug from url in wordpress

I’m trying to remove the attachment slug from the attachment URL generated by wordpress. My current URL structure looks like:

www.site.com/category/folder/attachment/file

I made a function for that but the url output I’m getting is www.site.com/folder/file, its missing the category. Any idea how I can fix that? Here is what I got so far:

function wpd_attachment_link( $link, $post_id ){
    $post = get_post( $post_id );
     $post_data = get_post($post->post_parent);
    return home_url( single_cat_title('', false)."/".$post_data->post_name."/". $post->post_title );
}
add_filter( 'attachment_link', 'wpd_attachment_link', 20, 2 );

P.S: i know that can be done if i change the permalink structure from the main wordpress menu, but dont want to change the current permalink structure.

Upvotes: 1

Views: 1287

Answers (1)

Bhumi Shah
Bhumi Shah

Reputation: 9476

Try following code:

function __filter_rewrite_rules( $rules )
{
    $_rules = array();
    foreach ( $rules as $rule => $rewrite )
    $_rules[ str_replace( 'attachment/', '/', $rule  ) ] = $rewrite;
    return $_rules;
}
add_filter( 'rewrite_rules_array', '__filter_rewrite_rules' );

function __filter_attachment_link( $link )
{
    return preg_replace( '#attachment/(.+)$#', '/$1', $link );
}
add_filter( 'attachment_link', '__filter_attachment_link' );

Upvotes: 1

Related Questions