How To Change Permalink Of Uploaded Media Files With Custom Code

You are currently viewing How To Change Permalink Of Uploaded Media Files With Custom Code

How To Change Permalink Of Uploaded Media Files With Custom Code

To set a custom permalink structure for uploaded media files using custom code, you can use the init action hook to register a new rewrite rule that will handle the permalinks for media files.

Here is an example of how you can do this:

Copy codefunction custom_media_permalinks() {
    // Register a new rewrite rule for media files
    add_rewrite_rule(
        '^media/([0-9]{4})/([0-9]{2})/([^/]*)/?',
        'index.php?attachment=$matches[3]',
        'top'
    );
}
add_action( 'init', 'custom_media_permalinks' );

This code will create a new rewrite rule that will handle permalinks in the format /media/YYYY/MM/media-filename/, where YYYY is the year and MM is the month.

To make sure that WordPress recognizes the custom permalink structure for media files, you will also need to add a custom query var and flush the rewrite rules. Here is an example of how you can do this:

Copy codefunction custom_media_query_vars( $vars ) {
    // Add a custom query var for media files
    $vars[] = 'attachment';
    return $vars;
}
add_filter( 'query_vars', 'custom_media_query_vars' );

function custom_media_rewrite_flush() {
    // Flush the rewrite rules to update the permalink structure for media files
    custom_media_permalinks();
    flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'custom_media_rewrite_flush' );

Place this code in your theme’s functions.php file or in a custom plugin. Remember to change the permalink structure in the add_rewrite_rule() function to match the desired custom structure for your media files.

Once you have added this code, the custom permalink structure will be applied to all media files, including images, audio, and video files. You can use the same technique to set custom permalink structures for other post types as well.

if you need any help in wordpress development click here

This Post Has 2 Comments

Leave a Reply