3
* Server-side rendering of the `core/categories` block.
9
* Renders the `core/categories` block on server.
11
* @param array $attributes The block attributes.
13
* @return string Returns the categories list/dropdown markup.
15
function render_block_core_categories( $attributes ) {
21
'hierarchical' => ! empty( $attributes['showHierarchy'] ),
23
'show_count' => ! empty( $attributes['showPostCounts'] ),
27
if ( ! empty( $attributes['displayAsDropdown'] ) ) {
28
$id = 'wp-block-categories-' . $block_id;
30
$args['show_option_none'] = __( 'Select Category' );
31
$wrapper_markup = '<div class="%1$s">%2$s</div>';
32
$items_markup = wp_dropdown_categories( $args );
36
$wrapper_markup .= build_dropdown_script_block_core_categories( $id );
39
$wrapper_markup = '<ul class="%1$s">%2$s</ul>';
40
$items_markup = wp_list_categories( $args );
44
$class = "wp-block-categories wp-block-categories-{$type}";
46
if ( isset( $attributes['align'] ) ) {
47
$class .= " align{$attributes['align']}";
50
if ( isset( $attributes['className'] ) ) {
51
$class .= " {$attributes['className']}";
54
$block_content = sprintf(
60
return $block_content;
64
* Generates the inline script for a categories dropdown field.
66
* @param string $dropdown_id ID of the dropdown field.
68
* @return string Returns the dropdown onChange redirection script.
70
function build_dropdown_script_block_core_categories( $dropdown_id ) {
73
<script type='text/javascript'>
76
var dropdown = document.getElementById( '<?php echo esc_js( $dropdown_id ); ?>' );
77
function onCatChange() {
78
if ( dropdown.options[ dropdown.selectedIndex ].value > 0 ) {
79
location.href = "<?php echo home_url(); ?>/?cat=" + dropdown.options[ dropdown.selectedIndex ].value;
82
dropdown.onchange = onCatChange;
87
return ob_get_clean();
91
* Registers the `core/categories` block on server.
93
function register_block_core_categories() {
97
'render_callback' => 'render_block_core_categories',
102
add_action( 'init', 'register_block_core_categories' );