Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active December 12, 2015 07:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hissy/4740436 to your computer and use it in GitHub Desktop.
Save hissy/4740436 to your computer and use it in GitHub Desktop.
[WordPress] wp_nav_menu のクラスに独自ルールを追加する
<?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');
@hissy
Copy link
Author

hissy commented Feb 8, 2013

$sorted_menu_items の返り値はWP_Postクラスのインスタンスの配列だが、nav_menu_item投稿タイプのオブジェクトなので、ナビメニューの項目ではなく、実際に表示される投稿の情報で条件分岐を行うには、object_idを用いてget_postを通さないといけない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment