sorry if this question has been asked before.

I have a few custom fields created with ACF and I am trying to push these fields to json, to use them in a js file.

My code looks like this:

function receiver_custom_fields() {
    foreach ( array('brand', 'name', 'cinema_dsp') as $field ) {
        register_rest_field( 'receiver', $field , array( 
            'get_callback' => function() {
                return get_field($field);

But I get this error:

Notice: Undefined variable: field in E:\xampp\htdocs\test-comparator\wp-content\themes\hifi-compare\functions.php on line 8

The fields: brand, name, and cinema_dsp are created.

I already created a function for each field and it works, but I want to add many more fields and I don't want to create a register_rest_field() function for each one.

What can I do?


1 Answer 1


The $field variable isn't available inside your get_callback() function. PHP isn't like JavaScript in that way, and that function can't access variables from outside its scope (unless it's global, but that's a poor solution).

To pass the $field variable through to the callback function, you need to write it like this:

'get_callback' => function() use ( $field ) {
    return get_field( $field );
  • Thank you, Jacob!
    – Catalin
    May 31, 2019 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.