Search code examples
wordpresstwigadvanced-custom-fieldstimber

Timber Twig get the filesize of a file from ACF field


I have an ACF field that is a file upload. I am able to get the attachment ID. However in my twig template I am not able to output the filesize as this is not available via ACF.

There is a function I have found:

$context['filesize'] = (filesize( get_attached_file(the_attachment_id_here))/1000 );

but what I really need it for it to be in twig loop.

I have tried in my template:

 {% for item in posts %} 
{{function(filesize( get_attached_file(item.get_field('pdf').id))/1000 )}}
{% endfor %

but it returns an error filesize unknown function.

Any help would be amazing!


Solution

  • Ooof, that's a nasty one —

    the real best way would be...

    First make a custom class for your Posts. Add a method to do the fetching and converting you're looking for ...

    class MyPost extends \Timber\Post {
    
      function pdf_filesize() {
        $pdf = $this->get_field('pdf');
        //you may need to convert the value of $pdf into an array...
        $file = get_attached_file($pdf['id']);
        return filesize($file) / 1000;
      }
    }
    

    And then anywhere you're fetching posts, use MyPost instead...

    $context['posts'] = Timber::get_posts(null, 'MyPost');
    

    In the Twig file...

    {% for post in posts %}
      File size is {{ post.pdf_filesize }}
    {% endfor %}
    

    If you just need to hack it...

    {% for item in posts %} 
        {{ function(
              'filesize', function(
                  'get_attached_file', item.get_field('pdf').id
               )
            ) / 1000 }}
    {% endfor % }