How to auto rename based on current post title a media defined as featured image
-
How to auto rename based on current post title a media defined as featured image
I’m using import plugin that defines terrible names for featured images, downloaded .jpg files and are as well with large and illegible names, I had a plugin that renamed all featured image based on post title, bulk rename – Rename Featured Image by hrishiv90, but not Works more in wp4.7, so I’m trying to solve this:
I tried to write a plugin:
function update_file_image_name($post_id){ $post = get_post( $post_ID ); $feat_image_this_post_trash = wp_get_attachment_url($post_id); $feat_image_this_post_friendly = sanitize_title( $post->post_title ); $feat_image_this_post_cleaned = str_replace($feat_image_this_post_trash, $feat_image_this_post_friendly, $feat_image_this_post_cleaned); } add_action( 'save_post', 'update_file_image_name' );
I want to apply the alt alt in my featured images, but with the files of strange names, large numbers and mixed letters, will be a bad SEO. I need the images to have the name of the title of the post, and that is in the act of creating the posts.
thanks all.
- This topic was modified 7 years, 7 months ago by herculesnetwork.
-
note: My lack of sleep made me try a str_replace like a creazy! But too the code bellow not is my.
Why does not this rename my images / uploads with the name of the post, but only with a number + dimensions? Uploads / 1-320×280.jpg? WordPress 4.7.4
function new_filename($filename, $filename_raw) { global $post; $info = pathinfo($filename); $ext = empty($info['extension']) ? '' : '.' . $info['extension']; $new = $post->post_title . $ext; // the if is to make sure the script goes into an indefinate loop if( $new != $filename_raw ) { $new = sanitize_file_name( $new ); } return $new; } add_filter('sanitize_file_name', 'new_filename', 10, 2);
thanks all.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
It is because in the context of when the sanitize_file_name filter fires, there is no valid global $post value. The global $post relates to template loops on the front end. It’s a different environment in the backend. While $post might be used here and there, it’s not something you can rely on. I suggest you remove your ‘sanitize_file_name’ filter callback because it is impacting other operations that you probably do not want to impact.
The ‘save_post’ callback is a good start, but there are several things to change. Instead of getting the attachment URL, get the entire object, you will need it. Workout the new filename from the post object being saved and the results of pathinfo(). Use the post_name (slug), not post_title. You should alter the attachment object’s title and name to match the parent post’s name.
Workout the complete path and set the attachment object’s guid field to the path. Alter the attachment’s meta data, key “_wp_attached_file” to the new name/path relative to the uploads folder, for example “2017/04/post-slug-as-filename.jpg”. There are references to all the reduced files in post meta key “_wp_attachment_metadata”. This is an array of data. Go through all the “file” elements and update the filename.
When you save the updated attachment object, the process will end up firing the “save_post” action again, causing infinite looping if measures aren’t taken. What you could do is initially hook “publish_post” instead of “save_post”. Attachment updates fire “save_post” but not “publish_post”. The other good thing about this hook is it only fires on publish and update, not draft and other statuses.
If there are any old references in post_content, they need to be updated too. When updating the main post, you do need to watch for infinite looping again. Maybe the first thing done on callback entry is to check if a particular static variable exists. If so, check it’s value against the passed ID. If it matches, return without doing anything. If it doesn’t exist, we can assume this is the initial entry and we can set a static variable to contain the current post ID.
Finally, you need to rename all the files on the server to the new value. Use rename() naturally. There will be problems if there are other references to this image file on other posts. It’d be a good idea to somehow be sure this is a newly attached image. Maybe by verifying all the dates are within a certain narrow range?
Before returning after doing all of that, in case this process is part of a loop of updates, unset the static variable so a new post can be processed. Otherwise you only get one chance per request to do anything.
That morning before I fainted from sleep, I was trying to get some things you’re teaching, but I still did almost everything wrong:
add_action('add_attachment', 'rename_attacment', 999, 3); function rename_attacment($post_ID){ $post = get_post($post_ID); $file = get_attached_file($post_ID); $path = pathinfo($file); //dirname = File Path //basename = Filename.Extension //extension = Extension //filename = Filename //$post = get_post( $post_ID ); //$newfilename = $post->post_title; $newfilename = "today will to be amazing"; $newfile = $path['dirname']."/".$newfilename.".".$path['extension']; rename($file, $newfile); update_attached_file( $post_ID, $newfile ); }
That way up, it always works, but only with string !! The same old case, but my mistake was trusting $ post again, I still had not read your help from that topic. So, the latest method is the least wrong for dispensing sanitize, I just have to change the use of $ post.
And also I have been trying to do directly in the plugin, it saves the obgect in $ image:
// hercules begin; // $post = get_post($post_ID); // $file = get_attached_file($post_ID); $file = $image; $path = pathinfo($file); //dirname = File Path //basename = Filename.Extension //extension = Extension //filename = Filename //$post = get_post( $post_ID ); //$newfilename = $post->post_title $newfilename = "to day will to be a great day"; $newfile = $path['dirname']."/".$newfilename.".".$path['extension']; rename($file, $newfile); rename($image, $file); // hercules and;
# but too not working! More than 80% of the things I have trying to do, I get to do it directly by modifying these plugins, which are the basis of my work, when I can do an external code, my plugins, which I have several, I’m even happier. But when it works directly in the original plugin files, I use this method. First I try to make it out, when I can not, I go to the guts of the plugins. This time it’s not working, I’ll work hard on your tips now.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
Ohh yes, I just noticed one thing, when you talked about taking care not to modify files with old dates that may contain associations that can be broken with the name name … I remembered to say that the important thing is all future posts come with new Image file names, the plugin that I miss very much, it rally rename all the image files already existent in the server according to the name of the posts to which the image was associated, but one thing I forgot to say, is that with The posts with bad names already exist, I do not need to worry, because the plugin that renames everything, stopped working shortly, I have to worry about future posts, and ideally, the images already enter the system With the friendly “correct” name, as I’m even trying to do it up, working directly on the $title and $image plugin objects, if you have a plugin like this that I wrote above, that only works with strings, because I’m using $post pulling frontend data! Idea and what simplifies more things, we will think to rename the image at the time of the posting, we can really forget the issue of renaming existing files with bad names, because simply, there are almost no bad name files, but many will come bad if I do not modify that crazy plugin that pulls images with crazy names. I have a second import plugin that already fixes this(And I do not understand(I’m beginner srs) the code of this import plugin that already arranges name of the images). This is the dirty plugin of “my repository”. Soon, if the plugin that made up the mess stopped working, then I thought I’d have something that would never let things mess up from now on.
this is the Messy plugin(The same as we used as an example for create auto import). Of course, this plugin is not available in the wordpress repository, it sells out, I do not even know if it would be in the curatorship, he’s so Messy, that I got his look, putting some more beautiful buttons, and Also correcting terms of writing.Messy Plugin: Messy Plugin
Thank You So Much.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
And in place in
$post;
Would be$wpdb;
And to pull an inner element of the post edit? Would be a field like:$slug = get_post_field ('post_name', get_post ());
?$wpdb is completely unrelated to $post. $wpdb is from class wpdb, a database connection class. $post is from WP_Post class, a class for a single post.
Assuming code is executing as part of a standard WP Loop, then you should be able to do
$slug = get_post()->post_name;
Since PHP 5.4 I believe.You are correct, setting a friendly image filename as the image is imported is ideal. Of course to do so, the post title needs to be available. You say you want to get the title from post edit? In the context of auto-import, what is post edit? Nothing is being edited, incoming data is compiled into a compatible format and inserted in the DB. Even if there was an editor, the title is not available to PHP until the post is saved because the editor is client side, PHP is server side.
If images are imported using wp_handle_sideload(), the filter ‘wp_unique_filename’ can be used to alter the default filename to something friendlier. One catch is the filename was already checked for no duplicates. When it is changed, we need to reverify there are no duplicates. The code to do this is relatively simple, it can be copied from the wp_unique_filename() source itself. It starts at line 2096 in the linked doc’s source code. After that you can see where are filter is applied. The code just keeps adding a number to the base name until one is found that does not exist.
We would not want to always match uploads to post names, so the filter should be selectively applied only when we want the behavior. The add_filter() call should be done from code that executes only for this auto-import.
This scheme would only work if the post title is already known and available. This probably means the post must be created or imported before the related image. Whether it is or not, what might be easier is to replicate how the post name is determined in the first place. There must be something in the remote data that is used to create the post name. Do the same thing to create the filename that is established in the ‘wp_unique_filename’ filter.
Many thanks for this too 🙂 :
while ( file_exists( $dir . "/$filename" ) ) { if ( '' == "$number$ext" ) { $filename = "$filename-" . ++$number; } else { $filename = str_replace( array( "-$number$ext", "$number$ext" ), "-" . ++$number . $ext, $filename ); } }
My brain is really frying with this:
This code works perfectly to modify the name of the file defined as featured image:
add_action('add_attachment', 'rename_attacment'); function rename_attacment($post_ID){ $post = get_post($post_ID); $file = get_attached_file($post_ID); $path = pathinfo($file); //dirname = File Path //basename = Filename.Extension //extension = Extension //filename = Filename //$friendly_name = get_the_title(); //$friendly_name = $post->post_title; $friendly_name = "NEW NAME TO IMAGES UPLOADED"; $newfilename = $friendly_name; $newfile = $path['dirname']."/".$newfilename.".".$path['extension']; rename($file, $newfile); update_attached_file( $post_ID, $newfile ); }
$file = get_attached_file($post_ID);
Is it being sufficient to get the object / file and restarts it, I do not know if we should worry about another way to pull the file, if that code already does the job, the file is always renamed successfully at the time of creating the post , Because it modifies the filename at the time that the image uploaded to my wordpress site, it arrives at the server, always work fine this code, the question here is to have the value of post_title to apply, or value of the slug, The case, both are good, because it always seems like it’s still done !! But I do not understand why, because it is not empty !!($post_ID),
was enough to open the image, and I modified it successfully, I do not understand why$post = get_post ($ post_ID);
Not for pulling post_title! I can not think that the title of the post is still empty when this action is triggered, because simply this code is working well to pull the image, which by the way, can only be work with the above code, if the post already exists, because It came out of the variable import plugin, if it is there inside the get_attached_file so I modify it, the title is certainly ready before it !! The image is the last thing the plugin import works, it first takes care of the other elements of the post, if that code works well in the image, why can not I get the value of the title? He already is in the$post_title
of wordpress!
The image is always renamed with just:.jpg
(without words, missing words!) using the value $post-> post_title; !! As if it had nothing inside the variable, but it has yes !! If you have in get_attached_file it’s also to have inpost_title
!
Then in the plugin, the object that holds the image of the thumb is $image which is then copied to:$thumbid
; Then beforeset_post_thumbnail ($post_id, $thumbid);
I do inside the import plugin, I did as the Castilian orders(or not 🙁 ):// hercules begin // $file = $thumbid; $path = pathinfo($thumbid); //dirname = File Path //basename = Filename.Extension //extension = Extension //filename = Filename //$friendly_name = $post_title; // $friendly_name = "NEW NAME TO IMAGES UPLOADED"; $friendly_name = $title_Item_x; //var used from this plugin $newfilename = $friendly_name; //$newfile = $path['dirname']."/".$newfilename.".".$path['extension']; $newfile = $newfilename.".".$path['extension']; // rename($thumbid, $title); rename($thumbid, $newfile); // hercules end set_post_thumbnail( $post_id, $thumbid );
My brain will melt, because when I insist on something, I do not stop! 🙁
- This reply was modified 7 years, 7 months ago by herculesnetwork.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
I has founded his code almost complete here on codex!!
“his code”!I tried a lot until the exhaustion did this from the outside, with our own plugin, but since I did not want to accept the title, nor convert it and everything else .. I went inside the plugin import in that case too, and I did : I just commented on that area where I said it looked like a big mess,
And I applied info in the variable that stores the image in the plugin, and concatenate the variable that stores the title + variable that stores the opted by the info extension, then, the sum of these variables and I applied in the basename of the plugin. If the data is already available within the plugin, I should not have endured so much trying to find them after posting in the publication; In short, I did it in two different ways, like those two code above that I said that work only with strings and not with post_title … so … doing those same things inside the plugin, it worked. I spent about 30 hours on this thing! Aafff .. I’m too tired now 🙁 .. but I did, thanks to you that it helps me a lot. Without your help I would not be able to. 😀
I’m going to eat something and get some sleep and let’s work on that automatic plugin firing with pre-filled fields 🙂 🙂 See you late my friend 😀
THANKKKSSS AAAALOTT. Thank you so much againYou are a crazy man! (the good kind of crazy) Reading your reports are very entertaining 🙂
The reason
$post = get_post($post_ID)
wasn’t working is $post_ID is the attachment ID! You were trying to get the title of the object you want to set the title for — circular reasoning. I think if you had taken the post_parent ID of that post and gotten the parent post, you would have had the title you were seeking. No matter since you found a solution. I’m telling you just as an explanation for better understanding.Because the process involves many things, there are many different ways to accomplish the same goal. As long as it works, any one of them are valid. I’m happy to hear you found one that works for you!
Hahaha good that my way of being comic / crazy amuses you, so I have a way to contribute minimally about something for you 🙂
I discovered that several posts were missing thumbs because of a bug in an update on one of the import plugins that I use .. so I thought, I’ll have to find a solution, I’m flooding the bcworkz with questions and our lesson about “auto Run a plugin” will not be paused again, noooooo… so I thought, so I do not need to use the your fantastic “update page’s bcwz” of the library via $wpdb; That you has created :-), (I would have to ask you how to edit it for to scan the posts without a featured image from my database and to delete) I’ll have to find something, so I found a plugin today, calling “Post List Featured Image” her is doing Many people very happy) because it adds a feature that misses the wordpress coming by default in it(or in an official plugin), which is a filter on the admin / posts list that we can filter shows all the posts with featured ima and without featured ima, or without featured ima.. this helps a lot in many cases, so [SOLVED], we mark in library media page,for that image used as featured image to be linked in another level to the post, level that to the we delete the post, and image go It goes together, and does not let the system forget any unused image on the system, uses the “sky remove” plugin, every time we delete a post, it takes along the used image in featured Image, the feature that would be good if wordpress had option(in an official plugin) 🙂 ..(I understand that a cms with everything ready is not ideal, because then it would be heavy, having the resources separately in plugins, it can get leaner and each person will put just the weight that it needs, but I’m sad with incredible plugins stopping work Because the developers abandon the times !, but I think there must be a balance between CMS not coming with these things, but not depending on third parties, wordpress team have more plugins like jetpack and others, deleting images along with the post, and List posts with filter posts without featured image has made me very happy, and the 10 users who voted also srsrsr, it is very useful indeed! , Not by the number of people, but the level of appreciation of the people, you realize that it was very essential, many should miss and do not know to find this plugin ), has plugin that do amazing things, but few people use and do not thank giving a good rating, I highly praise any plugin that I use and serves me. As I am still very poor and I can not donate, at least help with the minimum that is of notoriety to the developers who contribute so much to the lovely wordpress universe 🙂Everything was solved .. and in two days I call you in our “auto run a plugin” 😀
See you soon friend and thaaaannkksss so much 😀
- This reply was modified 7 years, 7 months ago by herculesnetwork.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
Yes, unsupported plugins are SO disappointing! You get used to it being available, create content that relies on it, and for a while everything is great. Then one day an update breaks the plugin and no one is able to patch the plugin. It has become useless code as does all your content that relies on it 🙁
This is not unique to WordPress or even open source. I have lots of commercial software acquired over the years that I really liked, some of which I paid substantial money for. It is all junk now and the content I made with it is useless. Such a waste!
I now try to write my own code whenever possible. As I’m responsible for maintaining it, I’ve only myself to blame if it remains broken. I cannot do it all though. When turning to others, it’s worth trying to stay with the most popular, well supported, frequently updated plugins. Of course, if you have specialized needs, that will not suffice. There is no good answer sometimes, except to not get too comfortable with unusual software. Always be ready for it to become suddenly inoperative with no possible fix.
Such a pessimistic way to live! It is not healthy, but the alternative is to be continually disappointed, which is also unhealthy. There is no good answer. Thank goodness for when things do go right, solving difficult problems through our own cleverness and skill. Very rewarding, bringing some happiness amid the sadness!
I hope you do not mind a bit of constructive criticism from a friend. While I enjoy your stream of consciousness style of writing, I wish you would remember to hit the return key twice every once in a while! Long blocks of text with no whitespace are difficult to read. Usually there are code snippets and things that help break up the text, but some whitespace helps define slight changes of thought.
If long blocks of text are intentional and you do not wish to do differently, that’s fine. But if it’s something you haven’t thought about, maybe you should 😛
Until next time!
Yes. Truth .. you’re absolutely right … And I really could not feel upset 🙂 I’m really distracted really, I unlock a lot of the time, I’m typing in a very continuous way! And forget to do the basics in the texts. Yes the text with paragraphs is the best way ever! And sometimes I get the text very often / continuous! But the editing time has expired! But the correct one was not having to edit, it would be better already and good way. I’ll improve this :-$
I’m going to call you on the other topic, I’m researching about keypress stock uploads, and I got to xdotool … I’m seeing alternative, I want the simplest possible method, I do not need user interface to do this cron, no fields and Buttons, I just want the same script … I have no preferences if it will be with javascript, xdottool or php, I just want to learn how to do this automation in some way.. I’ll call you there and Thanks againnnnn 😀 .
- This reply was modified 7 years, 7 months ago by herculesnetwork.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
- This reply was modified 7 years, 7 months ago by herculesnetwork.
can i have the full code for the plugin
- The topic ‘How to auto rename based on current post title a media defined as featured image’ is closed to new replies.