Luke Carbis It’s more complicated than 42.

5Apr/12Off

Add a parent menu class to wp_nav_menu

Today I needed to define a class for menu items that have a submenu. The menu items were outputted by wp_nav_menu, and I didn't want to use any Javascript.

I found a class filter for when items are being created, and so my first approach was to check if the page had sub pages, which seemed to work at first. I soon realised, however, that just because a page has children, it doesn't mean that it has child menu items, and pages without children can still have child menu items!

So here's my solution. Throw it in your themes functions.php file, and your wp_nav_menu items will receive the class 'parent-menu-item' if they have sub menu items.

function parent_menu_css_class( $classes, $item, $args ) {

    $menu_items = wp_get_nav_menu_items( $args->menu );

    if ( ! $menu_items && $args->theme_location && ( $locations = get_nav_menu_locations() ) && isset( $locations[ $args->theme_location ] ) ) :
        $menu = wp_get_nav_menu_object( $locations[ $args->theme_location ] );
        $menu_items = wp_get_nav_menu_items( $menu->term_id );
    endif;

    foreach ( $menu_items as $menu_item ) :

        if ( $menu_item->menu_item_parent == $item->ID ) :
            $classes[] = 'parent-menu-item';
            break;
        endif;

    endforeach;

    return $classes;
}
add_filter( 'nav_menu_css_class', 'parent_menu_css_class', 10, 3 );

Filed under: How To, Tech, Wordpress No Comments
2Apr/12Off

Including a Google Font in your WordPress theme the right way

Here's the best way to include a Google Font in your WordPress theme.

1. Prepare your font for use on Google Web Fonts. After you've chosen the styles and character sets you would like to include, copy the 'href' attribute of the include code. I'm using the font 'Neuton' in this example.

Copy this part!

2. In your theme's functions.php file, include the following code, substituting the red example font details for your own:

function enqueue_fonts() {
wp_register_style( 'neuton-font', 'http://fonts.googleapis.com/css?family=Neuton:300,700,400,400italic,200' );
wp_enqueue_style( 'neuton-font' );
}
add_action( 'init', 'enqueue_fonts' );

3. You're good to go - you can now use the font in your stylesheet, as per Google's instructions.

Filed under: How To, Tech, Wordpress No Comments