Created
January 19, 2016 15:05
-
-
Save jdhobbsuk/dc619f058416d8cfafb2 to your computer and use it in GitHub Desktop.
Get the file URL from ACF, including file type and size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get ACF File | |
* | |
* @param string $key – the ACF field key | |
* @param string $post_id – the ID of the post (if empty, will use $post->ID) | |
* @return string The image URL | |
**/ | |
function get_acf_file( $key = 'file', $post_id = '' ) { | |
if($post_id == ''): | |
global $post; | |
$post_id = $post->ID; | |
endif; | |
$file = get_field($key, $post_id); | |
if( !empty($file) ): | |
$file_url = $file['url']; | |
$file_type = get_file_type($file['mime_type']); | |
$file_size = get_file_size($file_url); | |
endif; | |
$file_details = array( | |
'url' => $file_url, | |
'type' => $file_type, | |
'size' => $file_size | |
); | |
return $file_details; | |
} | |
/** | |
* Get File Size | |
* | |
* @param string $file_url – passing in a file-type string | |
* @return string File type | |
**/ | |
function get_file_size( $file_url ) { | |
$file_info = array_change_key_case( get_headers($file_url, TRUE) ); | |
$file_size = file_size_convert( $file_info['content-length'] ); | |
return $file_size; | |
} | |
/** | |
* Convert Filesize | |
* | |
* @param string $bytes – bytes of | |
* @return string File type | |
**/ | |
function file_size_convert($bytes) { | |
$bytes = floatval($bytes); | |
$arBytes = array( | |
0 => array( | |
"UNIT" => "TB", | |
"VALUE" => pow(1024, 4) | |
), | |
1 => array( | |
"UNIT" => "GB", | |
"VALUE" => pow(1024, 3) | |
), | |
2 => array( | |
"UNIT" => "Mb", | |
"VALUE" => pow(1024, 2) | |
), | |
3 => array( | |
"UNIT" => "kB", | |
"VALUE" => 1024 | |
), | |
4 => array( | |
"UNIT" => "B", | |
"VALUE" => 1 | |
), | |
); | |
foreach($arBytes as $arItem) | |
{ | |
if($bytes >= $arItem["VALUE"]) | |
{ | |
$result = $bytes / $arItem["VALUE"]; | |
$result = str_replace(".", "," , strval(round($result, 0)))."".$arItem["UNIT"]; | |
break; | |
} | |
} | |
return $result; | |
} | |
/** | |
* Get File Type | |
* | |
* @param string $mime_type – passing in a file-type string | |
* @return string File type | |
**/ | |
function get_file_type( $mime_type ) { | |
if( preg_match('/msword/', $mime_type) || preg_match('/officedocument\.wordprocessingml\.document/', $mime_type) ): | |
$type = 'MS Word'; | |
elseif(preg_match('/pdf/', $mime_type)): | |
$type = 'PDF'; | |
elseif(preg_match('/ms-powerpoint/', $mime_type) || preg_match('/officedocument\.presentationml/', $mime_type) ): | |
$type = 'Powerpoint'; | |
endif; | |
return $type; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment