10up / gutenberg-best-practices

Welcome to the 10up Gutenberg Best Practices!
https://gutenberg.10up.com
87 stars 24 forks source link

Add Guide for building atomic blocks for post meta values to be used within the Query Loop #30

Open fabiankaegy opened 2 years ago

fabiankaegy commented 2 years ago

This is something that comes up again and again on client builds. Currently, the only way to show a meta value in the query loop is by building a custom block for it.

You can see some relevant discussions here:

fabiankaegy commented 2 years ago

As per a discussion in Slack I'm assigning this to @xavortm for now. Please let me know if you don't have the capacity to add a writeup and I will write one :)

fabiankaegy commented 2 years ago

@xavortm Sorry for not adding more information about what I was thinking here initially. I'll try to outline what I had in mind below.

The main question I keep seeing is how we can leverage the core query loop for custom post types that have custom meta values. An example of this would be a Books custom post type that has custom meta values like price, isdn_number, number_of_pages, etc.

As a user, I now want to be able to build a query loop to display all the different books. But I want to make sure the Price and number of pages are always shown on each item.

You can look at all the different post- blocks in Gutenberg core for how they do it. But essentially what you have done in your PR (#43) for the first example already is most of the way there. It reads the postId from the context which is either set by the current post/page the block gets inserted on. Or inside of the core/post-template that value gets set to the ID of the current post in the loop.

So my goal for the guide would be to combine the second example of your PR with the first one to showcase how you can display actual post meta values in the query loop like in the example of the price/number of pages for the books.