Rename files during upload within Wordpress backend - wordpress

is there a way to rename files during the upload progress within the Wordpress 3.0 backend? I would like to have a consistent naming of files, especially for images.
I think an 12 (+-) digit hash value of the original filename or something similar would be awesome. Any suggestions?
Regards

But it would really be easier to do that before uploading files.
Not quite sure about that - this seems fairly easy;
/**
* #link http://stackoverflow.com/a/3261107/247223
*/
function so_3261107_hash_filename( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
return md5( $name ) . $ext;
}
add_filter( 'sanitize_file_name', 'so_3261107_hash_filename', 10 );
This filter creates a 32 character hash of the original filename, preserving the file extension. You could chop it down a little using substr() if you wanted to.
This filter runs once the file has been uploaded to a temporary directory on your server, but before it is resized (if applicable) and saved to your uploads folder.
Note that there is no risk of file overwrite - in the event that a newly hashed file is the same as one that already exists, WordPress will try appending an incrementing digit to the filename until there is no longer a collision.
WordPress Plugin
<?php
/**
* Plugin Name: Hash Upload Filename
* Plugin URI: http://stackoverflow.com/questions/3259696
* Description: Rename uploaded files as the hash of their original.
* Version: 0.1
*/
/**
* Filter {#see sanitize_file_name()} and return an MD5 hash.
*
* #param string $filename
* #return string
*/
function so_3261107_hash_filename( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
return md5( $name ) . $ext;
}
add_filter( 'sanitize_file_name', 'so_3261107_hash_filename', 10 );

http://wpapi.com/change-image-name-to-wordpress-post-slug-during-upload/
BTW:
Add filter to sanitize_file_name is totally wrong, as sanitize_file_name() function is a helper function to format string, it may be used elsewhere like plugins or themes.
function wp_modify_uploaded_file_names($file) {
$info = pathinfo($file['name']);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($file['name'], $ext);
$file['name'] = uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $file;
}
add_filter('wp_handle_upload_prefilter', 'wp_modify_uploaded_file_names', 1, 1);

I've made a plugin for it. I did it because i was having too much trouble with my clients trying to upload images with special characters
http://wordpress.org/plugins/file-renaming-on-upload

I implemented the same thing, I wanted a more random filename, than the original, as the site I am using this for is for pics only and all files are in one directory.
i did the following
return md5($ip . uniqid(mt_rand(), true)) . $ext;

I was really looking for a plugin that could do it properly, and finally I ended up making this one myself. It's available on my blog: http://www.meow.fr/media-file-renamer ! If you use it, please give me a feedback :) I sincerely hope it helps!

You can't autorename file with the media library function. I would recommend to rename files before you upload them. Even after uploading a file you can't rename it throug WordPress but only through FTP.
The only way to do that would be a plugin that hooks itself into the media library upload process. But it would really be easier to do that before uploading files.

Related

contactform7 how attach any types files

earlier to attach files of any type to an email i commented lines in /modules/file.php
/* File type validation */
$file_type_pattern = wpcf7_acceptable_filetypes(
$tag->get_option( 'filetypes' ), 'regex'
);
$file_type_pattern = '/\.(' . $file_type_pattern . ')$/i';
if ( empty( $file['name'] )
or ! preg_match( $file_type_pattern, $file['name'] ) ) {
$result->invalidate( $tag,
wpcf7_get_message( 'upload_file_type_invalid' )
);
return $result;
}
this trick worked on version 5.3
after update does not work anymore
Anyone have any ideas how to get around this limitation without explicitly specifying allowed file types in plugin?
You can specify acceptable file types inside form tag:
[file file-123 filetypes:gif|png|jpg|jpeg]
https://contactform7.com/file-uploading-and-attachment/
Upd. It's might no way to specify any file type without editing plugin files now. Maybe it's better to determine what types of files exactly should be accepted. For example, it's not safe to allow .php files.

How Can I track sender's country after a cllient submits form via contact form 7?

Is there any mail-tags to use?
for instance; for tracking client's ip we can use; [_remote_ip]
First step is to create an API key. To get an API key we have to register in the site IPInfoDB.
Once API key is ready we have to download the file ip2locationlite.class.php from the site IPInfoDB.
Next step is to create our custom plugin.I named it as "country_custom_plugin.php". Its always good to create a custom plugin inside a folder, so that all the required files for the corresponding plugin stays in the folder. Named the folder as "country_custom_plugin"
Move the file "ip2locationlite.class.php" to the folder "country_custom_plugin".
/*Calling the function from contact-form-7 module and passing the result of the function stylus_ip_location_get_cc */
add_filter( 'wpcf7_special_mail_tags', 'country_custom_ip_location', 10, 2 );
/*Function to get location of an user from the ip address*/
function country_custom_ip_location( $output, $name ){
/*including the third party integration to get IP Location*/
include_once('ip2locationlite.class.php');
/*Special tag values are passed in format wpcf7.$name which we convert to _$name*/
$name = preg_replace( '/^wpcf7\./', '_', $name );
/*If location is requested in contact form enter the loop*/
if ( '_custom_ip_location' == $name ) {
$ipLite = new ip2location_lite;
/*Entering the API key value generated*/
$ipLite->setKey('"Enter your API Key Here"');
/*Getting the IP address*/
$ipaddress = preg_replace( '/[^0-9a-f.:, ]/', '', $_SERVER['REMOTE_ADDR'] );
/*Getting the Location*/
$visitorGeolocation = $ipLite->getCity($ipaddress);
if (!empty($visitorGeolocation) && is_array($visitorGeolocation)) {
$output = $visitorGeolocation['regionName'] . ', ' . $visitorGeolocation['countryName'] . ', ' . $visitorGeolocation['countryCode'];
}
}
return $output;
}
Reference.Hope this will help. Please let me know if any issue.

File path without domain name from wp_get_attachment_url()

wp_get_attachment_url() process full file path like
http://example.com/wp-content/uploads/2014/12/aura.mp3
I want the url without http://example.com/
So, I want above example as wp-content/uploads/2014/12/aura.mp3 instead of http://example.com/wp-content/uploads/2014/12/aura.mp3. How to do it?
You can really easily explode it by / and then take the part with index 3. Example
$url = wp_get_attachment_url(id); //id is file's id
$urllocal = explode(site_url(), $url)[1]; //output local path
Here is the WordPress way using WordPress functions (avoid hacking):
$fullsize_path = get_attached_file( $attachment_id ); // Full path
$filename_only = basename( get_attached_file( $attachment_id ) ); // Just the file name
WordPress has tons of functions, so first try to find the function on the docs: https://developer.wordpress.org/reference/functions/get_attached_file/
You can use PHP's function explode.
Here is the code:
<?php
$image_url = wp_get_attachment_url( 9 ); //ID of your attachment
$my_image_url = explode('/',$image_url,4);
echo $my_image_url[3];
?>
You can implode your entire url on / and array_slice from the end, then implode it back in on /.
$url = wp_get_attachment_url($item->ID); //id is file's id
$url_relative = implode(array_slice(explode('/', $url),-3,3),'/');
//Returns: 2019/08/image.jpg
That way if your WordPress is on a subdomain or localhost or the images are on S3 it won't crash.

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

Warning: Cannot modify header information

Warning: Cannot modify header information - headers already sent by (output started at /home/content/51/5126851/html/wp-includes/post-template.php:54) in /home/content/51/5126851/html/wp-includes/pluggable.php on line 890
I know I need to do something to my post-template.php file, but I'm not sure what. I looked at the other answers but mine seems a little different. Here's what the relevant function looks like:
/**
* Display or retrieve the current post title with optional content.
*
* #since 0.71
*
* #param string $before Optional. Content to prepend to the title.
* #param string $after Optional. Content to append to the title.
* #param bool $echo Optional, default to true.Whether to display or return.
* #return null|string Null on no title. String if $echo parameter is false.
*/
function the_title($before = '', $after = '', $echo = true) {
$title = get_the_title();
if ( strlen($title) == 0 )
return;
$title = $before . $title . $after;
if ( $echo )
echo $title; // <-- This is line 54 of post-template.php
else
return $title;
}
My first recommendation would be to learn how to format code for SO. And figure out how to cut down your problem to the bare minimum someone needs to solve it.
My second would be to look around the line mentioned in the error. I just did, and look what I found:
if ( $echo )
echo $title;
So now you know what's outputting stuff, what can you do about it?
Well, the other part of that statement is:
else
return $title;
Now, I'm no Wordpress expert, but I'm sure that you can work out the first thing that needs changing.
You shouldn't be editing files in wp-includes without a good reason and a good understanding of what you're doing. WordPress is extendable via themes and plugins in almost all situations - you should rarely, if ever, have to hack core code to do something.

Resources