1<?php
2/**
3 * Server-side rendering of the `core/term-count` block.
4 *
5 * @package WordPress
6 */
7
8/**
9 * Renders the `core/term-count` block on the server.
10 *
11 * @since 6.9.0
12 *
13 * @param array $attributes Block attributes.
14 * @param string $content Block default content.
15 * @param WP_Block $block Block instance.
16 *
17 * @return string Returns the count of the current taxonomy term wrapped inside a heading tag.
18 */
19function render_block_core_term_count( $attributes, $content, $block ) {
20 // Get term from context or from the current query.
21 if ( isset( $block->context['termId'] ) && isset( $block->context['taxonomy'] ) ) {
22 $term = get_term( $block->context['termId'], $block->context['taxonomy'] );
23 } else {
24 $term = get_queried_object();
25 if ( ! $term instanceof WP_Term ) {
26 $term = null;
27 }
28 }
29
30 if ( ! $term || is_wp_error( $term ) ) {
31 return '';
32 }
33
34 $term_count = $term->count;
35
36 // Format the term count based on bracket type.
37 switch ( $attributes['bracketType'] ) {
38 case 'none':
39 // No formatting needed.
40 break;
41 case 'round':
42 $term_count = "({$term_count})";
43 break;
44 case 'square':
45 $term_count = "[{$term_count}]";
46 break;
47 case 'curly':
48 $term_count = "{{$term_count}}";
49 break;
50 case 'angle':
51 $term_count = "<{$term_count}>";
52 break;
53 default:
54 // Default to no formatting for unknown types.
55 break;
56 }
57
58 $wrapper_attributes = get_block_wrapper_attributes();
59
60 return sprintf(
61 '<div %1$s>%2$s</div>',
62 $wrapper_attributes,
63 $term_count
64 );
65}
66
67/**
68 * Registers the `core/term-count` block on the server.
69 *
70 * @since 6.9.0
71 */
72function register_block_core_term_count() {
73 register_block_type_from_metadata(
74 __DIR__ . '/term-count',
75 array(
76 'render_callback' => 'render_block_core_term_count',
77 )
78 );
79}
80add_action( 'init', 'register_block_core_term_count' );
81