Skip to content

Instantly share code, notes, and snippets.

@donnamcmaster
Last active September 20, 2020 07:23
Show Gist options
  • Save donnamcmaster/d70ff26a553bc4072f108fde847cd7de to your computer and use it in GitHub Desktop.
Save donnamcmaster/d70ff26a553bc4072f108fde847cd7de to your computer and use it in GitHub Desktop.
WP shortcode: Bootstrap 4 dropdown menu button
<?php
/**
* 'button-menu' shortcode
* - insert a simple dropdown button menu
* - ref: https://getbootstrap.com/docs/4.2/components/dropdowns/
* - 'menu' parm should match a menu location
* - e.g., register_nav_menu( 'learning_grants', 'Learning Enrichment Grants' );
*/
add_shortcode( 'button-menu', function( $atts, $content=null ) {
extract( shortcode_atts(
array(
'menu' => '',
'title' => 'Select item',
'class' => 'btn btn-primary',
'id' => 'dropdownMenuButton', // only needs changing if multiple on page
),
$atts
));
$menu_items = wp_get_nav_menu_items( $menu );
if ( !$menu_items ) {
// mcw_log( "can't find $menu" );
return;
}
$this_ID = get_the_ID();
ob_start();
?>
<div class="button-menu-shortcode">
<button class="<?= $class;?> dropdown-toggle" type="button" id="<?= $id;?>" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $title;?>
</button>
<div class="dropdown-menu" aria-labelledby="<?= $id;?>">
<?php
foreach ( $menu_items as $key => $item ) {
$active_class = ( $item->object_id == $this_ID ) ? ' active' : '';
?>
<a class="dropdown-item<?= $active_class;?>" href="<?= $item->url;?>"><?= $item->title;?></a>
<?php
}
?>
</div>
</div>
<?php
return ob_get_clean();
});
@donnamcmaster
Copy link
Author

see example of use near the bottom of this page: https://cpsfoundation.org/grants-awards/learning-enrichment-grants/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment