|
| 1 | +import Experimental from "@site/docs/common/_experimental.md"; |
| 2 | +import CodeExample from "@site/src/components/CodeExample"; |
| 3 | + |
| 4 | +# Server side blocks |
| 5 | + |
| 6 | +<Experimental /> |
| 7 | + |
| 8 | +The `<server-side>` element can be used to render a block server side using the `<ServerSideRender />` component from `@wordpress/server-side-render` package. |
| 9 | + |
| 10 | +To use it, first install the package with: |
| 11 | + |
| 12 | +``` |
| 13 | +npm install @wordpress/server-side-render --save |
| 14 | +``` |
| 15 | + |
| 16 | +## Rendering blocks on the server |
| 17 | + |
| 18 | +To render a block on the server, use the `<server-block>` element with the `name` attribute telling it which block to render. |
| 19 | +It uses the same API as the `<block>` element to define attributes. |
| 20 | + |
| 21 | +<CodeExample> |
| 22 | + ``` |
| 23 | + <section> |
| 24 | + <server-block name="custom/latest-posts-slider" postType="pages"> |
| 25 | + <attribute name="numberOfPosts">5</attribute> |
| 26 | + </server-block> |
| 27 | + </section> |
| 28 | + ``` |
| 29 | +</CodeExample> |
| 30 | + |
| 31 | +## When to use server side blocks |
| 32 | + |
| 33 | +Server side blocks are particularly useful when having to query posts, build listing pages, more generaly whenever you need to build a data-rich block. |
| 34 | + |
| 35 | +To build a block that display the latest posts from our site, we could first define a block in HTML that will be used in the editor and that will render itself on the server: |
| 36 | + |
| 37 | +```html title="custom/latest-posts.html" |
| 38 | +<section> |
| 39 | + <server-block name="custom/latest-posts"></server-block> |
| 40 | +</section> |
| 41 | +``` |
| 42 | + |
| 43 | +Then, we can define a `render.php` override by creating a `latest-posts.render.php` file alongside our `latest-posts.html` file that will get the latest posts and render them: |
| 44 | + |
| 45 | +```php title="custom/latest-posts.render.php" |
| 46 | +<?php |
| 47 | + |
| 48 | +// You custom query here |
| 49 | +$latest_posts = get_posts(); |
| 50 | + |
| 51 | +?> |
| 52 | + |
| 53 | +<section <?= get_block_wrapper_attributes(); ?>> |
| 54 | +<?php foreach ($posts as $post) : ?> |
| 55 | + <article> |
| 56 | + <h3><?= $post->post_title; ?></h3> |
| 57 | + <a href="<?= get_permalink($post); ?>">Read more</a> |
| 58 | + </article> |
| 59 | +<?php endforeach; ?> |
| 60 | +</section> |
| 61 | + |
| 62 | +``` |
0 commit comments