How to add custom post type archive to menu

Viewed 18346

I have been searching for weeks and I still haven't found a proper solution to this problem.

I am writing a Wordpress Theme. I have a custom post type called Works. I would like to add my Works archive to my menu and have it as well as it's posts highlighted when I access them.

I can access my archive and posts on the following links

Works archive: /works/

Works single post: /works/postname/

My solution so fare have been to name my archive-works.php template file with a template name (Work archive). Then create an empty page using that template and adding the page to the menu. This highlights the archive in the menu but not the single posts.

I can easily solve this with a custom link and some javascript but there must be a better and cleaner way.

5 Answers

Navigate to Appearance > Menus;

Make sure you have the Works' custom post type selected at Screen Options;

Click on the name of your custom post type to expand it and then click on the ‘View all’ tab;

You will see an option for All Works. Check the box next to it and then click on the Add to Menu button;

Your custom post type archive will now appear as a menu item in the right column;

By default, the label will be "All Works". You can change this by writing something different at the Navigation Label;

Click on the Save Menu button to save your changes.

I found a solution on GitHub and it works out of the box by simply adding it to the functions.php without any walkers or extra classes.

This code solves it by comparing the slug of the current post type with the navigation items, and adds a class accordingly.

Code on GitHub

Related