Last active
December 12, 2015 07:58
-
-
Save hissy/4740436 to your computer and use it in GitHub Desktop.
[WordPress] wp_nav_menu のクラスに独自ルールを追加する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function nav_menu_class_customize($sorted_menu_items) { | |
foreach ($sorted_menu_items as $sorted_menu_item) { | |
// if menu item is a post type object (is not an archive or custom) | |
if ($sorted_menu_item->type == 'post_type') { | |
// get post object from object id | |
$post_obj = get_post($sorted_menu_item->object_id); | |
// rules | |
if ($post_obj->post_name == 'hoge') { | |
$sorted_menu_item->classes[] = 'this-page-is-hoge'; | |
} | |
} | |
} | |
return $sorted_menu_items; | |
} | |
add_filter('wp_nav_menu_objects','nav_menu_class_customize'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$sorted_menu_items の返り値はWP_Postクラスのインスタンスの配列だが、nav_menu_item投稿タイプのオブジェクトなので、ナビメニューの項目ではなく、実際に表示される投稿の情報で条件分岐を行うには、object_idを用いてget_postを通さないといけない。