WordPress function: limit size, only jpg, jpeg, limit of uploaded files per account

You cannot check the image before uploading, as WordPress is a serverside script.

However, before inserting the image in the Media library, you have different options, as I explained in this answer, with filtering wp_handle_upload_prefilter.

In your case, the function filtering the wp_handle_upload_prefilter would be something like this:

add_filter('wp_handle_upload_prefilter', 'f711_image_size_prevent');
function f711_image_size_prevent($file) {

    // get filesize of upload
    $size = $file['size'];
    $size = $size / 1024; // Calculate down to KB

    // get imagetype of upload
    $type = $file['type'];
    $is_image = strpos($type, 'image');

    // set sizelimit
    $limit = 700; // Your Filesize in KB

    // set imagelimit
    $imagelimit = 7;

    // set allowed imagetype
    $imagetype="image/jpeg";

    // query how many images the current user already uploaded
    global $current_user;
    $args = array(
        'orderby'         => 'post_date',
        'order'           => 'DESC',
        'numberposts'     => -1,
        'post_type'       => 'attachment',
        'author'          => $current_user->ID,
    );
    $attachmentsbyuser = get_posts( $args );

    if ( ( $size > $limit ) && ($is_image !== false) ) { // check if the image is small enough
        $file['error'] = 'Image files must be smaller than '.$limit.'KB';
    } elseif ( $type != $imagetype ) { // check if image type is allowed
        $file['error'] = 'Image must be ' . $imagetype . '.';
    } elseif ( count( $attachmentsbyuser ) >= $imagelimit ) { // check if the user has exceeded the image limit
        $file['error'] = 'Image limit of ' . $imagelimit . ' is exceeded for this user.';
    }
    return $file;

}

Leave a Comment