query-no-results.php 1.6 KB

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