| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/query-loop` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/query-loop` block on the server. |
| 10 |
* |
| 11 |
* @param array $attributes Block attributes. |
| 12 |
* @param string $content Block default content. |
| 13 |
* @param WP_Block $block Block instance. |
| 14 |
* |
| 15 |
* @return string Returns the output of the query, structured using the layout defined by the block's inner blocks. |
| 16 |
*/ |
| 17 |
function gutenberg_render_block_core_query_loop( $attributes, $content, $block ) { |
| 18 |
$page_key = isset( $block->context['queryId'] ) ? 'query-' . $block->context['queryId'] . '-page' : 'query-page'; |
| 19 |
$page = empty( $_GET[ $page_key ] ) ? 1 : filter_var( $_GET[ $page_key ], FILTER_VALIDATE_INT ); |
| 20 |
|
| 21 |
$query = array( |
| 22 |
'post_type' => 'post', |
| 23 |
'offset' => isset( $block->context['query']['perPage'] ) ? ( $block->context['query']['perPage'] * ( $page - 1 ) + $block->context['query']['offset'] ) : 0, |
| 24 |
'category__in' => $block->context['query']['categoryIds'], |
| 25 |
); |
| 26 |
if ( isset( $block->context['query']['perPage'] ) ) { |
| 27 |
$query['posts_per_page'] = $block->context['query']['perPage']; |
| 28 |
} |
| 29 |
$posts = get_posts( $query ); |
| 30 |
|
| 31 |
$content = ''; |
| 32 |
foreach ( $posts as $post ) { |
| 33 |
$content .= ( |
| 34 |
new WP_Block( |
| 35 |
$block->parsed_block, |
| 36 |
array( |
| 37 |
'postType' => $post->post_type, |
| 38 |
'postId' => $post->ID, |
| 39 |
) |
| 40 |
) |
| 41 |
)->render( array( 'dynamic' => false ) ); |
| 42 |
} |
| 43 |
return $content; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Registers the `core/query-loop` block on the server. |
| 48 |
*/ |
| 49 |
function gutenberg_register_block_core_query_loop() { |
| 50 |
register_block_type_from_metadata( |
| 51 |
__DIR__ . '/query-loop', |
| 52 |
array( |
| 53 |
'render_callback' => 'gutenberg_render_block_core_query_loop', |
| 54 |
'skip_inner_blocks' => true, |
| 55 |
) |
| 56 |
); |
| 57 |
} |
| 58 |
add_action( 'init', 'gutenberg_register_block_core_query_loop', 20 ); |
| 59 |
|