I set up a custom block in “WP Grid Builder” to get the file size from the ACF “File” field. I referenced a post here to get the code to do this, but nothing is outputting on the front end.
The block part loads fine with WP Grid Builder, so I’m assuming it is just the ACF function that needs to be figured out.
I don’t have any php experience, but the code appears to be implemented correctly. Can anyone see if I’m missing anything here?
add_filter(
'wp_grid_builder/blocks',
function( $blocks ) {
$blocks['file_size_block'] = [
'name' => __( 'File Size Block', 'text-domain' ),
'render_callback' => function() {
$attachment_id = get_field('report_attachment');
$url = wp_get_attachment_url( $attachment_id );
$title = get_the_title( $attachment_id );
// part where to get the filesize
$filesize = filesize( get_attached_file( $attachment_id ) );
$filesize = size_format($filesize, 2);
// show custom fields
if (get_field('report_attachment')):
echo ('<p>' . $filesize . '</p>');
endif;
},
];
return $blocks;
}
);
Thanks in advance for your help! 🙂
Going to preface this with “I do not know much about the block editor”
However, what I do know is if the field is set in a different block then you won’t be able to get a value from a different block do show it, or from a different post. When getting a field from somewhere else you generally need to provide the post ID that the value is associated with. https://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/
Thanks for the reply, John!
You are correct, calling the post was the missing piece.
Here’s the code that worked for me if anyone else is in need:
$blocks['file_size_block'] = [
'name' => __( 'File Size Block', 'text-domain' ),
'render_callback' => function() {
// Object can be a post, term or user.
$object = wpgb_get_object();
// If this is not a post (you may change this condition for user or term).
if ( ! isset( $object->post_type ) ) {
return;
}
$attachment_id = get_post_meta( $object->ID, 'report_attachment', true );
$file_path = get_attached_file( $attachment_id );
if ( empty( $attachment_id ) ) {
return;
}
// Get the file size
$file_size = filesize( $file_path );
// Return file size in megabytes
$file_size = round( $file_size / 1024, 0 );
echo $file_size . ' KB';
Cheers!
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.