Skip to content

Instantly share code, notes, and snippets.

@craigiswayne
Created June 16, 2017 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigiswayne/fc119f466c43e836cc4cf33426650b91 to your computer and use it in GitHub Desktop.
Save craigiswayne/fc119f466c43e836cc4cf33426650b91 to your computer and use it in GitHub Desktop.
Create an Off Canvas Menu with WordPress and UIKIT

Create an Off Canvas Menu with WordPress and UIKIT

Add the following to your functions.php file

add_action ( 'init', function(){
  $menu_locations = [
    'off_canvas' => __( 'Off Canvas' )
  ];
  register_nav_menus( $menu_locations );
} );

add_filter( 'wp_nav_menu_args', function( Array $args ){

    /**
     * Fail if the requested location does not exist
     */
    $desired_location = 'off_canvas';
    if ( empty( $args[ 'theme_location' ] ) || $args[ 'theme_location' ] !== $desired_location ) {
        return $args;
    }

    $existing_locations = get_nav_menu_locations();
    if ( ! array_key_exists( $desired_location, $existing_locations ) ) {
        return $args;
    }

    $menu_args         = [
        'menu_class'      => 'uk-nav uk-nav-offcanvas',
        'container'       => 'nav',
        'container_class' => 'uk-offcanvas-bar',
        'fallback_cb'     => null,
        'theme_location'  => $desired_location,
        'items_wrap'      => $off_canvas_header . $args[ 'items_wrap' ] . $off_canvas_footer
    ];

    $args = wp_parse_args( $menu_args, $args );
    return $args;
} );

Then in your header.php file you can add the following where you would like the offcanvas hamburger icon to sit

$off_canvas_menu_args = [
  'theme_location' => 'off_canvas'
];

if( has_nav_menu( $off_canvas_menu_args ) ){
  wp_nav_menu($off_canvas_menu_args);  
}

<?php
add_action ( 'init', function(){
$menu_locations = [
'off_canvas' => __( 'Off Canvas' )
];
register_nav_menus( $menu_locations );
} );
add_filter( 'wp_nav_menu_args', function( Array $args ){
/**
* Fail if the requested location does not exist
*/
$desired_location = 'off_canvas';
if ( empty( $args[ 'theme_location' ] ) || $args[ 'theme_location' ] !== $desired_location ) {
return $args;
}
$existing_locations = get_nav_menu_locations();
if ( ! array_key_exists( $desired_location, $existing_locations ) ) {
return $args;
}
$menu_args = [
'menu_class' => 'uk-nav uk-nav-offcanvas',
'container' => 'nav',
'container_class' => 'uk-offcanvas-bar',
'fallback_cb' => null,
'theme_location' => $desired_location,
'items_wrap' => $off_canvas_header . $args[ 'items_wrap' ] . $off_canvas_footer
];
$args = wp_parse_args( $menu_args, $args );
return $args;
} );
<?php
$off_canvas_menu_args = [
'theme_location' => 'off_canvas'
];
if( has_nav_menu( $off_canvas_menu_args ) ){
wp_nav_menu($off_canvas_menu_args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment