• Hi there
    I have a list of custom fields that I want to make available using the WP Rest API. I don’t think typing out all of this code for 20+ custom fields is the most efficient way?

    add_action( 'rest_api_init', 'slug_register_twitter' );
    function slug_register_twitter() {
        register_rest_field( 'shop',
            'twitter',
            array(
                'get_callback'    => 'slug_get_twitter',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    }
    
    function slug_get_twitter( $object, $field_name, $request ) {
        return get_post_meta( $object[ 'id' ], $field_name, true );
    }

    Can I do this as an array? I have the list but got a bit stuck as there are a couple of errors with the $value.

    $arr = array("email",  "facebook",  "friday_close",  "friday_open",  "google_plus",  "instagram",  "monday_close",  "monday_open",  "opening_days",  "pinterest",  "saturday_close",  "saturday_open",  "shop_number",  "shop_style",  "slideshow_1",  "slideshow_2",  "slideshow_3",  "sunday_close",  "sunday_open",  "telephone",  "thursday_close",  "thursday_open",  "tuesday_close",  "tuesday_open",  "twitter",  "twitter_widget",  "website",  "wednesday_close",  "wednesday_open",  "xmas",  "youtube");
    foreach ($arr as $value) {
    
      add_action( 'rest_api_init', 'slug_register_$value' );
    function slug_register_$value() {
        register_rest_field( 'shop',
            '$value',
            array(
                'get_callback'    => 'slug_get_$value',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    }
    
    function slug_get_$value( $object, $field_name, $request ) {
        return get_post_meta( $object[ 'id' ], $field_name, true );
    }
    }

    Where am I going wrong? Please help.

    https://wordpress.org/plugins/rest-api/

The topic ‘How to make all custom fields available using an array?’ is closed to new replies.