How can I register multiple custom post fields to json?

sorry if this question has been asked before.I have a few custom fields created with ACF and I am trying to push these f

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?

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?

Share Improve this question edited May 30, 2019 at 13:13 fuxia 107k39 gold badges255 silver badges459 bronze badges asked May 30, 2019 at 13:00 CatalinCatalin 134 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

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 );
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745451030a4628267.html

相关推荐

  • How can I register multiple custom post fields to json?

    sorry if this question has been asked before.I have a few custom fields created with ACF and I am trying to push these f

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信