Skip to content

Instantly share code, notes, and snippets.

@EugeneCib
Created October 29, 2015 13:14
Show Gist options
  • Save EugeneCib/fe58225a4c4815231938 to your computer and use it in GitHub Desktop.
Save EugeneCib/fe58225a4c4815231938 to your computer and use it in GitHub Desktop.
Timber acf file wrapper function
<?php
class BasePost extends TimberPost
{
public function get_file($key) {
$id = $this->get_field($key);
$file_path = get_attached_file( $id );
$file = new SplFileInfo($file_path);
try {
$data = [
'url' => wp_get_attachment_url( $id ),
'extension' => $file->getExtension(),
'size' => $this->format_bytes($file->getSize()),
'file_info' => $file,
];
} catch(Exception $e) {
$data = null;
}
return $data;
}
// @link from http://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
function format_bytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment