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.
Thanks
Thanks to rasmussvanejensen for her/his nice question and thethangtran for the answer, I am still confused why Wordpress has not yet added such a good feature to its code base by default.
By the way I think there is even a better solution than the one provided by thethangtran, as it may break on some situations.
Note 1
According to the Codex, using register_post_type, one can add extra
post_type
s to the installation. There is chance, some one need to change the 'query_var' and thus the provided code will break.Note 2
In addition, it may not handle the
current-menu-item
class, which will be used for css customization to show the menu item as active.Note 3
As another note on the code, there is no need to define the
loop_index
,item
anditems
variables. they are absolutely useless.A better solution
So I suggest using this alternative, for those who want a more robust solution to on this:
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.
To add "custom posttype archive link" to menu, please look at the following guide
Open file functions.php , and enter code below
You can do a simple trick in your functions.php:
In your case, you just have to add a class 'works-menu-item' with that archive menu item by the admin panel;