In my WP v6.1.1, my permalinks structure for posts is www.example.com/%postname%/
.
With this my uploaded media files permalink URLs (not File URL
) are taking away the slugs which we intended to use for actual posts.
With below code I wanted to rewrite the media (images) file permalink like www.example.com/img/imagename/
without changing the default upload folder.
add_action('init', 'custom_init');
function custom_init() {
global $wp_rewrite;
$url_structure = '/img/%img_postname%/';
$wp_rewrite->add_permastruct('attachment', $url_structure, false);
$wp_rewrite->add_rewrite_tag("%img_postname%", '([^/]+)', "attachment=");
}
In another post_type_link
filter function, I am converting the variable %img_postname%
into post_name
.
However, my media permalink URLs still are www.example.com/imagename
not www.example.com/img/imagename
My Answer:
To set a custom permalink structure for uploaded media files in WordPress, you can use the following code:
php
add_action('init', 'custom_init');
function custom_init() {
global $wp_rewrite;
$url_structure = '/img/%postname%/'; // Custom permalink structure for media files
$wp_rewrite->add_permastruct('attachment', $url_structure, false);
$wp_rewrite->add_rewrite_tag('%postname%', '([^/]+)', 'attachment=');
}
function custom_post_link($permalink, $post) {
if ($post->post_type == 'attachment') {
$post_name = $post->post_name;
$permalink = home_url('/img/' . $post_name . '/');
}
return $permalink;
}
add_filter('post_type_link', 'custom_post_link', 10, 2);
This code will set the custom permalink structure for uploaded media files to be www.example.com/img/imagename/. The `custom_init` function adds the custom permalink structure for media files, and the `custom_post_link` function filters the permalink for media files to include the custom structure.
Make sure to replace `img` with your desired slug for media files in the `$url_structure` variable. This code should be added to your theme's `functions.php` file or a custom plugin.
Rate this post
3 of 5 based on 6708 votesComments