将精选图像添加到wp_nav_menu项目

Dre*_*ker 6 wordpress menu filter

这是一个自我问答.

如何修改wp_nav_menu输出中出现的text/html?例如,我想为页面和类别添加特色图像.

您可以看到使用自定义walker执行此操作的示例,但代码对于小更改非常复杂.当然有一种方法可以使用过滤器吗?

Dre*_*ker 13

这是我想出的代码,感谢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;
}
Run Code Online (Sandbox Code Playgroud)

然后,您需要构建代码以从传递给过滤器的$ 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;
}
Run Code Online (Sandbox Code Playgroud)

然后,您要删除在开头应用的过滤器,以便处理的下一个菜单不使用与filter_menu_items()中定义的相同的HTML.

// 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;
}
Run Code Online (Sandbox Code Playgroud)