0

I need a menu that features (in that order): index page, a custom page, first post category page, second post category page, and another custom page.

I can't understand how to do it with wordpress functions, so I just did links with static href attributes, as following: /, /some-page, /category/foo, /category/bar, /another-page.

This works, but now I can't (or don't know how to) add an active class to the menu item corresponding to the current page.

Also, I would like the active class to apply to the menu item corresponding to the category of the post when displaying a single post, i.e. if I click on a post from category foo, active class should still be applied to the menu item going to /category/foo.

Could you tell me whether there exist a proper way to do this?

2

Use a Navigation Menu. In your child theme or custom theme's functions.php file, create the menu like so:

add_action('after_setup_theme', 'wpse_add_theme_support');
function wpse_add_theme_support() {
    add_theme_support('menus');
}
add_action('init', 'wpse_nav_menus');
function wpse_nav_menus() {
    register_nav_menu( 'primary-menu', __( 'Primary Menu', 'theme-slug' ) );
}

Then presumably in header.php, or wherever you're adding the menu:

wp_nav_menu(array('theme_location' => 'primary-menu');

There are various other parameters to customize the menu, from its container to before to after and custom walkers if the HTML markup doesn't end up being what you need.

Once that's all set up in your theme, there are currently 2 places within wp-admin where you'll be able to add items to your menu. One is in the Customizer (Appearance > Customize) and the other is in Nav Menus (Appearance > Menus). Make sure if you use the Menus area to double-check the little Screen Options tab. You can toggle what type of items are available there, from categories to posts to pages, custom post types to manual links. As much as possible, use WordPress' built-in functionality (such as choosing a Category from the Categories pane) because if you ever change the name or permalink, WP will automatically update your menu for you. If you use Custom Links those are frozen in time and you'll have to remember to manage them manually.

You'll probably need to use a custom walker to add your active class. Build out the nav menu first and make sure all that is working, then post back if you have trouble figuring out the walker part.

  • 1
    Thanks. I managed somehow to assemble a walker that does what I want from other walkers found on the internet and some trial&error. You made the concept of wordpress menus much clearer for me. – Fiodor May 25 '17 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.