Custom Fields
Re-Envisioned
Support MB Relationships Relationships in Custom REST API Endpoint

  • Creator
    Topic
  • #26924
    Resolved BRIAN WERTZ
    Participant

    Hi -

    I'm creating a custom REST endpoint and I'm having trouble populating Metabox Fields.

    website returns true/false and cities is null.

    Thanks for your help!

    if( !class_exists( 'toAPI' ) ) {
    
        class toAPI {
          function __construct() {
            add_action( 'rest_api_init', [$this, 'init'] );
          }
        
          function init() {
            register_rest_route( 'to/v1', '/destinations', [
              'methods' => 'GET',
              'callback' => [$this, 'get_destinations'],
            ] );
        
            }
        
          // Get recent destinations
          function get_destinations( $params ) {
            $destinations =  get_posts( [
              'post_type' => 'destinations',
              'posts_per_page' => 10
            ] );
        
            foreach( $destinations as &$d ) {
              $d->thumbnail = get_the_post_thumbnail_url( $d->ID );
              $d->website = rwmb_meta( 'website' );
              $d->cities = MB_Relationships_API::get_connected( [
                    'id'   => 'destination-city',
                    'to' => $d->ID, // You can pass object ID or full object
                ] );
                foreach ( $d->cities as &$c ) {
                    $c->post_title;
                    $c->id;
                }
            }
        
            return $destinations;
          }
        
        
        }
        
        new toAPI();
        }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
    Replies
  • #26933
    Long Nguyen
    Moderator

    Hi Brian,

    Thank you for reaching out.

    website: if you are using the helper function rwmb_meta() in a custom loop, you have to pass 3 arguments as in the documentation https://docs.metabox.io/rwmb-meta/#arguments.

    It should be: $d->website = rwmb_meta( 'website', '', $d->ID );

    cities: return null means there is no post connect to a post type destinations. Is that a post type destinations connect to another post type? So the argument should change to from

    'id'   => 'destination-city',
    'from' => $d->ID,
    #27039
    BRIAN WERTZ
    Participant

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.