• Sorry if this is an amateur question. I’m a javascript developer.

    Right now I have a function that gets the content of the field cta_text for each custom post type of promotions.

    How would I iterate through this code to add multiple custom fields? i.e. cta_text, cta_url, etc

    add_action('rest_api_init', 'register_post_custom_field');
    function register_post_custom_field() {
            register_api_field( 'promotions',
                'cta_text',
                array(
                    'get_callback'    => 'get_custom_field',
                    'update_callback' => null,
                    'schema'          => null,
                )
            );
        }
    
    function get_custom_field( $object, $field_name, $request ) {
            return get_post_meta( $object[ 'id' ], $field_name, true );
        }
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Assuming the only variable that changes in each iteration is the field name, i.e. the callback is the same in all cases, then first you build an array of field names to serve as the source data that drives the iterative loop. Then you use a foreach loop that uses the array and within the loop calls register_api_field() with the current field name. Like this:

    $names = array('cta_text', 'cta_url', 'cta_foo', 'cta_bar',);
    foreach ( $names as $name ) {
           register_api_field( 'promotions',
                $name,
                array(
                    'get_callback'    => 'get_custom_field',
                    'update_callback' => null,
                    'schema'          => null,
                )
            );
    }

    If each iteration has more than one variable, you can build a more complex data array. An array of arrays for example. Then the foreach is adjusted to work with the complex structure. You could even nest foreach loops to work with the array of arrays structure.

    You can also use associative array keys as part of the data used. Another form of foreach looks like this:

    $names = array( 'cta_text' => 'callback_foo',
        'cta_url' => 'callback_bar', );
    foreach ( $names as $key => $value ) {
        my_function( $key, $value);
    }

Viewing 1 replies (of 1 total)
  • The topic ‘WP-API Multiple Custom Post Custom Fields’ is closed to new replies.