Relationships in Custom REST API Endpoint

Support MB Relationships Relationships in Custom REST API EndpointResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #26924
    BRIAN WERTZBRIAN 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();
        }
    #26933
    Long NguyenLong 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 WERTZBRIAN WERTZ
    Participant

    Thank you!

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