|
1 <?php |
|
2 /** |
|
3 * Server-side rendering of the `core/query-total` block. |
|
4 * |
|
5 * @package WordPress |
|
6 */ |
|
7 |
|
8 /** |
|
9 * Renders the `query-total` block on the server. |
|
10 * |
|
11 * @since 6.8.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 The rendered block content. |
|
20 */ |
|
21 function render_block_core_query_total( $attributes, $content, $block ) { |
|
22 global $wp_query; |
|
23 $wrapper_attributes = get_block_wrapper_attributes(); |
|
24 if ( isset( $block->context['query']['inherit'] ) && $block->context['query']['inherit'] ) { |
|
25 $query_to_use = $wp_query; |
|
26 $current_page = max( 1, (int) get_query_var( 'paged', 1 ) ); |
|
27 } else { |
|
28 $page_key = isset( $block->context['queryId'] ) ? 'query-' . $block->context['queryId'] . '-page' : 'query-page'; |
|
29 $current_page = isset( $_GET[ $page_key ] ) ? (int) $_GET[ $page_key ] : 1; |
|
30 $query_to_use = new WP_Query( build_query_vars_from_query_block( $block, $current_page ) ); |
|
31 } |
|
32 |
|
33 $max_rows = $query_to_use->found_posts; |
|
34 $posts_per_page = (int) $query_to_use->get( 'posts_per_page' ); |
|
35 |
|
36 // Calculate the range of posts being displayed. |
|
37 $start = ( 0 === $max_rows ) ? 0 : ( ( $current_page - 1 ) * $posts_per_page + 1 ); |
|
38 $end = min( $start + $posts_per_page - 1, $max_rows ); |
|
39 |
|
40 // Prepare the display based on the `displayType` attribute. |
|
41 $output = ''; |
|
42 switch ( $attributes['displayType'] ) { |
|
43 case 'range-display': |
|
44 if ( $start === $end ) { |
|
45 $output = sprintf( |
|
46 /* translators: 1: Start index of posts, 2: Total number of posts */ |
|
47 __( 'Displaying %1$s of %2$s' ), |
|
48 $start, |
|
49 $max_rows |
|
50 ); |
|
51 } else { |
|
52 $output = sprintf( |
|
53 /* translators: 1: Start index of posts, 2: End index of posts, 3: Total number of posts */ |
|
54 __( 'Displaying %1$s – %2$s of %3$s' ), |
|
55 $start, |
|
56 $end, |
|
57 $max_rows |
|
58 ); |
|
59 } |
|
60 |
|
61 break; |
|
62 |
|
63 case 'total-results': |
|
64 default: |
|
65 // translators: %d: number of results. |
|
66 $output = sprintf( _n( '%d result found', '%d results found', $max_rows ), $max_rows ); |
|
67 break; |
|
68 } |
|
69 |
|
70 return sprintf( |
|
71 '<div %1$s>%2$s</div>', |
|
72 $wrapper_attributes, |
|
73 $output |
|
74 ); |
|
75 } |
|
76 |
|
77 /** |
|
78 * Registers the `query-total` block. |
|
79 * |
|
80 * @since 6.8.0 |
|
81 */ |
|
82 function register_block_core_query_total() { |
|
83 register_block_type_from_metadata( |
|
84 __DIR__ . '/query-total', |
|
85 array( |
|
86 'render_callback' => 'render_block_core_query_total', |
|
87 ) |
|
88 ); |
|
89 } |
|
90 add_action( 'init', 'register_block_core_query_total' ); |