Site icon Hip-Hop Website Design and Development

WP default file upload hook not working if used in a plugin

WP version: 4.7.2

I’m creating a plugin and I use wp_handle_upload_prefilter & wp_handle_sideload_prefilter to filter file size and return errors.

When added to the theme’s functions.php, both are working. But when added to the plugin functionality, wp_handle_sideload_prefilter won’t work anymore.

Someone have any idea how to make this hook work inside a plugin?

Here’s my function:

function validate_user_storage_space( $file ) {

    $storage_limits = array(
        "administrator" => 1, //size in MB
        "editor" => 0,
        "author" => 0,
        "contributor" => 0,
        "subscriber" => 0,
        "client" => 0,
        "vendor-basic" => 1,
        "pending_user" => 0,
        "suspended" => 0,
    );

    //$storage_limits = get_option( $this->plugin_name );

    $user_id = get_current_user_id();
    $user_data = get_userdata( $user_id );
    $user_roles = $user_data->roles;

    $user_limits = array();

    // If user has multiple roles
    foreach ( $user_roles as $role ) {
        array_push( $user_limits, $storage_limits[ $role ] );
    }

    // Sorts the limits in ascending order
    sort( $user_limits );

    // 9999 limit means unlimited storage
    if ( end( $user_limits ) === 9999 ) {
        return $file;
    }
    else {
        // returns the highest limit
        $size_limit = end( $user_limits );
    }

    // Convert MB to Bytes
    $size_limit_bytes = $size_limit * pow( 1024, 2 );

    $used_storage_space = get_user_meta( $user_id, 'rbsl_used_storage_space', $single = true );
    $file_size = $file[ 'size' ];

    if ( ( $file_size + $used_storage_space ) > $size_limit_bytes ) {
        $storage_limit_reached = true;
    }
    else {
        $storage_limit_reached = false;
    }

    if ( $file[ 'size' ] > 1 ) {
        $file['error'] = apply_filters( 'rbsl_sl_error_message', __( 'You've reached the limit of', $this->plugin_name ) . ' ' . $size_limit . 'MB', $size_limit );
    }

    return $file;

}
add_filter('wp_handle_upload_prefilter', 'validate_user_storage_space', 1);
add_filter('wp_handle_sideload_prefilter', 'validate_user_storage_space', 1);