如果在插件中使用,WP默认文件上载挂钩不起作用

时间:2017-02-18 作者:marccaps

WP版本:4.7.2

我正在创建一个插件,我使用wp_handle_upload_prefilter &;wp_handle_sideload_prefilter 筛选文件大小并返回错误。

当添加到主题的functions.php, 两者都在发挥作用。但当添加到插件功能时,wp_handle_sideload_prefilter 再也不行了。

有人知道如何让这个钩子在插件中工作吗?

以下是我的功能:

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

1 个回复
SO网友:Anwer AR

大概validate_user_storage_space 发射太早或太迟。尝试将此函数包装到另一个函数中,然后用下面的一个动作钩子钩住第二个函数

initafter_setup_themeplugins_loaded

如下所示。

add_action( \'init\', \'validate_user_init\' ); //after_setup_theme plugins_loaded
function validate_user_init(){
  add_filter(\'wp_handle_upload_prefilter\', \'validate_user_storage_space\', 1);
  add_filter(\'wp_handle_sideload_prefilter\', \'validate_user_storage_space\', 1);
}

function validate_user_storage_space( $file ) {
 //your stuff
}

相关推荐

当返回wp_errors或0时,如何设置条件标签

我正在提交前端帖子。我几乎完成了。在前端成功提交帖子后,我想重定向到特定页面。我正在使用此函数。wp_insert_post( array $postarr, bool $wp_error = false ) 这将返回:成功时的帖子ID。失败时的值0或WP\\U错误。$post_id = wp_insert_post( $post_data ); if( !$post_id || ?? ){ wp_redirect( site_url(\'/compledted/\')