admin管理员组文章数量:1334812
Currently, when uploading an image, Wordpress automatically uses the image name as image title. Is there a way to automatically use current date for the image title?
Currently, when uploading an image, Wordpress automatically uses the image name as image title. Is there a way to automatically use current date for the image title?
Share Improve this question asked Jun 16, 2020 at 19:02 Uni LegUni Leg 31 bronze badge1 Answer
Reset to default 0You can achieve this by using following code:
/* Automatically set the image Title, Alt-Text, Caption & Description upon upload
--------------------------------------------------------------------------------------*/
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$custom_title = date("Y-m-d"); //settings current date as title
$my_image_details = get_post( $post_ID )->post_title;
// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_details = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$my_image_details = ucwords( strtolower( $my_image_title ) );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $custom_title , // Set image Title to date
'post_excerpt' => $my_image_details , // Set image Caption (Excerpt) to sanitized title
'post_content' => $my_image_details , // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
Here I'm replacing image title with date and description with actual formatted title. This action will run every time you upload a new image.
本文标签: Image title replace with current date
版权声明:本文标题:Image title replace with current date 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742343461a2457050.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论