图像标题替换为当前日期

时间:2020-06-16 作者:Uni Leg

目前,在上传图像时,Wordpress会自动使用图像名称作为图像标题。有没有办法自动使用图像标题的当前日期?

1 个回复
最合适的回答,由SO网友:Sabbir Hasan 整理而成

您可以通过使用以下代码来实现这一点:

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

    } 
}
在这里,我用日期替换图像标题,用实际格式的标题替换描述。每次上载新图像时,都将运行此操作。

相关推荐

Wordpress cutting images size

我目前正在制作一个页面的横幅,过了一段时间,我注意到我的图像质量比我预期的稍差一些。我上传了1920x1024大小的图片,但在我查看管理仪表板后,我注意到它们已经缩小到1024x575!这有什么原因吗?有什么办法可以防止这种情况发生吗?提前感谢!