1<?php
2/**
3 * Server-side rendering of the `core/query-no-results` block.
4 *
5 * @package WordPress
6 */
7
8/**
9 * Renders the `core/query-no-results` block on the server.
10 *
11 * @since 6.0.0
12 *
13 * @global WP_Query $wp_query WordPress Query object.
14 *
15 * @param array $attributes Block attributes.
16 * @param string $content Block default content.
17 * @param WP_Block $block Block instance.
18 *
19 * @return string Returns the wrapper for the no results block.
20 */
21function render_block_core_query_no_results( $attributes, $content, $block ) {
22 if ( empty( trim( $content ) ) ) {
23 return '';
24 }
25
26 $page_key = isset( $block->context['queryId'] ) ? 'query-' . $block->context['queryId'] . '-page' : 'query-page';
27 $page = empty( $_GET[ $page_key ] ) ? 1 : (int) $_GET[ $page_key ];
28
29 // Override the custom query with the global query if needed.
30 $use_global_query = ( isset( $block->context['query']['inherit'] ) && $block->context['query']['inherit'] );
31 if ( $use_global_query ) {
32 global $wp_query;
33 $query = $wp_query;
34 } else {
35 $query_args = build_query_vars_from_query_block( $block, $page );
36 $query = new WP_Query( $query_args );
37 }
38
39 if ( $query->post_count > 0 ) {
40 return '';
41 }
42
43 $classes = ( isset( $attributes['style']['elements']['link']['color']['text'] ) ) ? 'has-link-color' : '';
44 $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $classes ) );
45 return sprintf(
46 '<div %1$s>%2$s</div>',
47 $wrapper_attributes,
48 $content
49 );
50}
51
52/**
53 * Registers the `core/query-no-results` block on the server.
54 *
55 * @since 6.0.0
56 */
57function register_block_core_query_no_results() {
58 register_block_type_from_metadata(
59 __DIR__ . '/query-no-results',
60 array(
61 'render_callback' => 'render_block_core_query_no_results',
62 )
63 );
64}
65add_action( 'init', 'register_block_core_query_no_results' );
66