Search code examples
wordpressurlgalleryslugshortcode

Change wordpress gallery shortcode slug to filename


Is it possible to change the attachment page slug to the referring filename? In short... i use the Gallery Shortcode to build a simple page based gallery.

I change the orignal filename (like DSC1223.jpg) during the upload process (to 3b1871561aab.jpg) but it does not appery as slug within the url. It uses only DSC1223.

Is there anyway to change ist?

Regards, Steve

The best way would be to write something like this in my functions.php

function twentyten_filter_wp_handle_upload () {

    $upload =  wp_handle_upload();

}

add_filter( 'wp_handle_upload', 'twentyten_filter_wp_handle_upload', 10, 2);

Solution

  • Add this to the hash upload filename plugin and you should be good to go;

    /**
     * Filter new attachments and set the post_name the same as the hashed
     * filename.
     * 
     * @param int $post_ID
     */
    function change_attachment_name_to_hash($post_ID)
    {
        $file = get_attached_file($post_ID);
        $info = pathinfo($file);
        $name = trim( substr($info['basename'], 0, -(1 + strlen($info['extension'])) ) );
        wp_update_post(array(
            'ID' => $post_ID,
            'post_name' => $name
        ));
    }
    add_action('add_attachment', 'change_attachment_name_to_hash');
    

    Don't hesitate to ask if you're not sure what each line does!

    UPDATE:

    This function hooks onto the add_attachment event, just after a new attachment is saved to the database. This action is called from within wp_insert_attachment().

    We first grab the filename of the attachment (get_attached_file()). Then we use a native PHP function pathinfo() to get the path components, and strip the directory path and file extension away.

    Then we call wp_update_post(), updating the post_name of the attachment in the database.