cearls / timberland

A modern WordPress theme using Timber, Advanced Custom Fields Pro, Vite, Tailwind and Alpine.js
MIT License
78 stars 19 forks source link

Access ACF Fields from functions.php of a Block #41

Closed joannerpena closed 1 month ago

joannerpena commented 2 months ago

I've been trying to do some API Call on a block using the ACF fields as parameters to the call. However, I haven't been able to get access to the fields directly from PHP on the Functions.php of the block which makes the call function to the API not work.

Is there any way of achieving this?

calico-digital commented 2 months ago

I ran into this issue and whilst it probably isn't the cleanest code this works for me. In the acf_block_render_callback function in functions.php, I replaced with this:

function acf_block_render_callback($block, $content) {
    $context = Timber::context();
    $context['post'] = Timber::get_post();
    $context['block'] = $block;
    $context['fields'] = get_fields();
    $name = str_replace('-', '_', str_replace(' ', '_', str_replace('acf/', '', $block['name'])));
    require_once dirname(__FILE__) . "/blocks/{$name}/functions.php";
    $setupFunc = "setup_{$name}";

    if (function_exists($setupFunc)) {
        $context['fields'] = array_merge($context['fields'], $setupFunc($context['fields']));
    }

    $template = $block['path'] . '/index.twig';

    Timber::render($template, $context);
}

Then in the block functions.php file, you can add in a function like setup_block( $fields ) which you can then add to or manipulate with PHP.

Hope this helps.

cearls commented 2 months ago

Thanks for helping out with a solution @calico-digital!

joannerpena commented 2 months ago

@calico-digital Thank you, I will give it a try and let you guys know how it goes.