我正在尝试将自定义字段信息从页面获取到导航菜单中。我以前遇到过这个问题...我只是不“了解”步行者菜单及其工作原理。
基本上,除了页面标题之外,我还想让它从自定义字段输出图像的 URL 和图像描述,并创建一个链接到普通 WP 页面的菜单项。
在 nav-menu-template.php 文件中,我尝试通过添加 get_post_custom_keys() 来修改 start_el 函数,如下所示,但没有成功:
$item_output .= '<a'. $attributes .'>';
$item_output .= get_post_custom_values("product_image", $item->ID);
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
我也尝试过 get_post_meta();以及其他取得有限成功的人。我能做的最好的事情就是通过指定一个硬整数值来获取在所有链接中重复的图像之一。或者,我已经能够让它以文本形式输出正确的帖子/页面值,但没有图像。
有人知道解决方案吗..我做错了什么?
迭代导航菜单并动态渲染它可能会更容易。下面的代码将让您迭代指定的导航菜单,该导航菜单分配给您在functions.php 文件中注册的导航菜单位置:
<ul id="some-menu-id" class="my-fancy-menu">
<?php
$menu_name = 'primary';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
foreach ( (array) $menu_items as $key => $menu_item ) {
// at this point you can get the custom meta from the page
$image = get_post_meta($menu_item->object_id, '_custom_field_image_url', true);
$image_description = get_post_meta($menu_item->object_id, '_custom_field_image_description', true);
// here we are getting the title and URL to the page
$title = $menu_item->title;
$url = $menu_item->url;
$slug = basename($menu_item->url);
// this allows us to add a current class
if (basename($_SERVER['REQUEST_URI']) == $slug) { $current = ' current-menu-item'; } else { $current = ''; }
$menu_list .= '<li class="page-id-'.$menu_item->object_id.$current.'"><a href="' . $url . '">' . $title . '</a><br /><p>'.$image_description.'<br />'.$image.'</p></li>';
}
}
echo $menu_list;
?>
</ul>
wp_nav_menu( array(
'menu' => 'primary',
'walker' => new WPDocs_Walker_Nav_Menu()
)
);
// Custom Nav Menu walker class.
class WPDocs_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
// Depth-dependent classes.
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
$display_depth = ( $depth + 1); // because it counts the first submenu as 0
// Custom nav menu item custom field value i want to get in the $classes.
$menu_color = '"style="background-color: $item->Description""';
// Combine values of classes.
$classes = array(
'dropdown-menu',
( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),
( $display_depth >=2 ? 'sub-sub-menu' : '' ),
'menu-depth-' . $display_depth,
''. $menu_color
);
$class_names = implode( ' ', $classes );
// Build HTML for output.
$output .= ($depth == 0) ? "\n" . $indent . '<ul class="' . $class_names . '">' . "\n" . "\n <div class=\"megamenu-content\">\n" . "\n<div class=\"row\">\n" : "\n<ul class=\"elementy-ul\">\n";
}
// Start the element output codes from here.....
}