Skip to content

Commit

Permalink
Add frontend scripts for the Categories block in dropdown mode
Browse files Browse the repository at this point in the history
  • Loading branch information
tyxla committed Aug 3, 2017
1 parent 2893607 commit 2dfb411
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/blocks/categories.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,15 @@ function gutenberg_render_block_core_categories( $attributes ) {
);

if ( ! empty( $attributes['displayAsDropdown'] ) ) {
$id = 'wp-block-categories-' . wp_rand();
$args['id'] = $id;
$wrapper_markup = '<div class="%1$s">%2$s</div>';
$items_markup = wp_dropdown_categories( $args );
$type = 'dropdown';

if ( ! is_admin() ) {
$wrapper_markup .= gutenberg_build_dropdown_script_block_core_categories( $id );
}
} else {
$wrapper_markup = '<div class="%1$s"><ul>%2$s</ul></div>';
$items_markup = wp_list_categories( $args );
Expand All @@ -47,6 +53,33 @@ function gutenberg_render_block_core_categories( $attributes ) {
return $block_content;
}

/**
* Generates the inline script for a categories dropdown field.
*
* @param string $dropdown_id ID of the dropdown field.
*
* @return string Returns the dropdown onChange redirection script.
*/
function gutenberg_build_dropdown_script_block_core_categories( $dropdown_id ) {
ob_start();
?>
<script type='text/javascript'>
/* <![CDATA[ */
(function() {
var dropdown = document.getElementById( '<?php echo esc_js( $dropdown_id ); ?>' );
function onCatChange() {
if ( dropdown.options[ dropdown.selectedIndex ].value > 0 ) {
location.href = "<?php echo home_url(); ?>/?cat=" + dropdown.options[ dropdown.selectedIndex ].value;
}
}
dropdown.onchange = onCatChange;
})();
/* ]]> */
</script>
<?php
return ob_get_clean();
}

register_block_type( 'core/categories', array(
'render_callback' => 'gutenberg_render_block_core_categories',
) );

0 comments on commit 2dfb411

Please sign in to comment.