WordPress覆盖旧的上传文件

时间:2014-08-19 12:57:55

标签: wordpress wordpress-plugin

如何在上传与以前上传的文件同名的文件时设置WordPress覆盖文件?默认情况下,WordPress会更改文件名。如果我将文件上传为image1.png并尝试上传具有相同文件名的新文件,则第二个文件将是name image11.png。我希望WordPress用新文件替换旧文件。这可能吗?

1 个答案:

答案 0 :(得分:1)

将以下内容添加到functions.php文件中应该有效:

add_filter( 'sanitize_file_name', 'filename_filter_wpse_28439', 10, 1 );

function filename_filter_wpse_28439( $name ) 
{
    $args = array(
        'numberposts'   => -1,
        'post_type'     => 'attachment',
        'meta_query' => array(
                array( 
                    'key' => '_wp_attached_file',
                    'value' => $name,
                    'compare' => 'LIKE'
                )
            )
    );
    $attachments_to_remove = get_posts( $args );

    foreach( $attachments_to_remove as $attach )
        wp_delete_attachment( $attach->ID, true );

    return $name;
}

如果你上传了一个已上传的文件,它将覆盖该图像。以上内容来自here,但在WordPress 3.9.2上进行了测试

相关问题