Skip to content

Instantly share code, notes, and snippets.

@senlin
Created June 5, 2014 05:28
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 senlin/b9484f63da15e11ceb2b to your computer and use it in GitHub Desktop.
Save senlin/b9484f63da15e11ceb2b to your computer and use it in GitHub Desktop.
Custom Walker of Flatbook theme that adds # in front of menu items to enable one-page website
<?php
/**
* Custom Walker used in Flatbook theme
*
* @source //themeforest.net/item/flatbook-flat-ebook-selling-wordpress-theme/6023410
* @ref //lnkd.in/dRjx4R6
*/
class description_walker extends Walker_Nav_Menu{
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0){
//global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'><i class="fa '.$item->attr_title.'"></i>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
if($item->object == 'page'){
$varpost = get_post($item->object_id);
$attributes .= ' href="' . get_site_url() . '#' . $varpost->post_name . '"';
} else
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$args = (object) $args;
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID );
$item_output .= $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args, $id );
}
}
Copy link

ghost commented Jun 7, 2014

I used this script to create anchor links for my custom posts in the navigation menu's.
(I created custom post types to have sections on a single page layout, and the generated URL's needed a hash preceding the postname, because the link had to point to a local ID anchor on the same page)

Instantiating this class as the custom menu walker did the trick perfectly.
The only thing I had to change was line 20 where the script says:
if($item->object == 'page')
I changed 'Page' to my own custom post type, et voila! The trick was done.

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