gpt4 book ai didi

wordpress - 将特色图像添加到 wp_nav_menu 项目

转载 作者:行者123 更新时间:2023-12-02 23:38:39 25 4
gpt4 key购买 nike

这是一个 self 问答。

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

您会看到使用自定义步行器执行此操作的示例,但对于小的更改来说,代码非常复杂。当然有办法用过滤器来做到这一点吗?

最佳答案

这是我在 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;
}

然后您想要删除在开始时应用的过滤器,以便处理的下一个菜单不会使用上面在 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;
}

关于wordpress - 将特色图像添加到 wp_nav_menu 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com