I’m creating menu in wordpress and I would like add class=”active” to link when its page is active. I’m not using inbuilt wordpress menu feature.
I’m making menu hardcoded in header.php because this menus are linked to custom posttype archive pages. So I would like to keep class active if one is inside single or archive page of that posttype.
Here is what i would like to do:
header.php
<?php if ($post_type == "custom_post_type1") : ?>
<li><a href="link_to_post_type1_story" class="active">Post type 1</a><li>
<?php else: ?>
<li><a href="link_to_post_type1_story">Post type 1</a><li>
<?php endif; ?>
<?php if ($post_type == "custom_post_type2") : ?>
<li><a href="link_to_post_type2_story" class="active">Post type 2</a><li>
<?php else: ?>
<li><a href="link_to_post_type2_story">Post type 2</a><li>
<?php endif; ?>
I hope I explained what I’m looking for well.
Thanks.
you can use get_queried_object, as
get_post_type
does not work on custom post type (I don’t know yet why, more info here)then you can proceed with
I’ve tested this in one of the sites I’m working on, I hope it work on yours too..
EDIT:
here is the new code that you can use for archives too:
I’ve added a taxonomy type too in case you would need one yourself.
You can still use the built in menu, even when linking to custom types archive… You just need to insert a custom link with the URL of the custom archive page (in the menu creation page, at the left, click on “link”. Like this you don’t need to worry about creating the classes manually, and the menu will be easier to maintain 🙂
You can use the function get_post_type
Where
$post
is the ID or the object of the post you want to check.