2014-09-27 59 views
4

這是一個自調Q & A.添加功能的圖像wp_nav_menu項目

你如何修改的text/html出現在wp_nav_menu的輸出?例如,我想爲頁面和類別添加精選圖片。

您會看到使用自定義walker進行此操作的示例,但代碼對於進行小的更改非常複雜。當然有一種方法可以用過濾器來做到這一點?

回答

9

這是我想出的代碼感謝來自Wordpress StackOverflow答案的一些幫助,我找不到了(如果找到它,請點擊鏈接評論)。

首先,您需要將過濾器添加到特定菜單(如果需要,您可以將其添加到所有菜單 - 只需使用add_filter行)。

// Add filter to specific menus 
add_filter('wp_nav_menu_args', 'add_filter_to_menus'); 
function add_filter_to_menus($args) { 

    // You can test agasint things like $args['menu'], $args['menu_id'] or $args['theme_location'] 
    if($args['theme_location'] == 'header_menu') { 
     add_filter('wp_setup_nav_menu_item', 'filter_menu_items'); 
    } 

    return $args; 
} 

然後,您需要構建代碼以從傳遞給過濾器的$ item對象獲取帖子或類別ID。這並不像您期望的那麼容易,因爲$ item不包含底層的帖子/類別ID,只是菜單項ID。所以我使用URL來反向查找ID。

這不適用於菜單或自定義分類法中使用的標籤。我只需要它的類別,所以這是我建立的。

// Filter menu 
function filter_menu_items($item) { 

    if($item->type == 'taxonomy') { 

     // For category menu items 
     $cat_base = get_option('category_base'); 
     if(empty($cat_base)) { 
      $cat_base = 'category'; 
     } 

     // Get the path to the category (excluding the home and category base parts of the URL) 
     $cat_path = str_replace(home_url().'/'.$cat_base, '', $item->url); 

     // Get category and image ID 
     $cat = get_category_by_path($cat_path, true); 
     $thumb_id = get_term_meta($cat->term_id, '_term_image_id', true); // I'm using the 'Simple Term Meta' plugin to store an attachment ID as the featured image 

    } else { 
     // Get post and image ID 
     $post_id = url_to_postid($item->url); 
     $thumb_id = get_post_thumbnail_id($post_id); 
    } 

    if(!empty($thumb_id)) { 
     // Make the title just be the featured image. 
     $item->title = wp_get_attachment_image($thumb_id, 'poster'); 
    } 

    return $item; 
} 

然後你想刪除您應用之初,這樣處理的下一個菜單沒有使用相同的HTML作爲上述filter_menu_items()定義的過濾器。

// Remove filters 
add_filter('wp_nav_menu_items','remove_filter_from_menus', 10, 2); 
function remove_filter_from_menus($nav, $args) { 
    remove_filter('wp_setup_nav_menu_item', 'filter_menu_items'); 
    return $nav; 
}