Change wordpress gallery shortcode slug to filename

為{幸葍}努か 提交于 2020-01-17 03:27:05

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/3265350/change-wordpress-gallery-shortcode-slug-to-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!