1

I have an app developed using ionic 2, is about quotes. I want to manage the quotes (and authors, categories, etc) with Wordpress and his REST API. At first instance i used normal posts, but now i am trying with custom post types, becouse that gives me more control and organization in the backend, so i have one CPT for quotes and other for authors, and a relation between them.

Example ↓

wp-json/wp/v2/quotes

[
  {
    id: 79,
    x_metadata: {
      custom_post_type_onomies_relationship: "77",
      quote: "Be yourself; everyone else is already taken"
    }
  }
]

wp-json/wp/v2/authors

[
  {
    id: 77,
    title: {
      rendered: "Oscar Wilde"
    },
    x_metadata: {
      bio: "https://wikipedia.org/wiki/Oscar_Wilde"
    }
  }
]

Like you can see, the relation is in custom_post_type_onomies_relationship, but i don't know how to merge this data properly in the app (in which i use Angular 2/Typescript).

The only way i can think is loop through the quotes, for every quote loop through authors checking ids, and then add the data from the author inside the quotes array. Is that okey or is there any other way more efficient?

Thanks in advance and sorry if my english is not perfect.

ragnarswanson
  • 315
  • 3
  • 10
aluknot
  • 504
  • 2
  • 7
  • 20
  • 1
    Wordpress has so many tables that is only for relationships. They are required to `many-to-many` structures. When I used wordpress as API, I made my own back-end with `ruby on rails`, but I had access to the database. You must search about `many-to-many` relationship. These loops are not efficient. – Raphael Parreira Apr 12 '17 at 03:59

1 Answers1

1

You can use _embed request for author

wp-json/wp/v2/quotes?_embed=

see embedding

updated

the embed resources are available only for certain fields (eg. post's author, replies)

The only way i can think is loop through the quotes, for every quote loop through authors checking ids, and then add the data from the author inside the quotes array.

if you want some linked data that not included (embeddable) the common pattern to minimize REST API calls is getting list of all authors then create array map of author_id -> authors stored in client

  • nested loop performance is O(n^2)
  • loop through the quotes then doing indexed search (authors[id] or Array.indexOf) performance is O(n*logn)

more: array search performance in JS

Community
  • 1
  • 1
aifarfa
  • 3,939
  • 2
  • 23
  • 35