我正在使用高级自定义字段将图像添加到各个菜单项。这些图像将附加到$item->title
使用以下代码:
function wp3456789_wp_nav_menu_objects( $items, $args ) {
foreach( $items as &$item ) {
$image = get_field(\'icon\', $item);
if( $image ) {
$item->title .= \'<span class="inline-img\' . $item->class . \'"><img class="style-svg" src="\' . $image[\'url\'] . \'" width="" height="" alt="\' . $image[\'alt\'] . \'" /></span>\';
}
}
return $items;
}
add_filter(\'wp_nav_menu_objects\', \'wp3456789_wp_nav_menu_objects\', 10, 2);
我需要
<span>
并在
$item->title
文本
这些图像将使用SVG支持插件替换为style-svg
班
例如:
<a href="#">
<span class="inline-img">
<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
<!-- SVG image -->
</svg>
</span>
Menu Item Title
</a>
The
wp_nav_menu
用于呈现菜单的代码:
$args = array(
\'theme_location\' => \'global-footer-navigation\',
\'menu_id\' => \'global-footer-navigation\',
\'container\' => false,
\'echo\' => false,
\'items_wrap\' => \'%3$s\',
\'depth\' => 0,
);
// Strip all remaining menu HTML except for <a>, <span>, and <img> tags
echo strip_tags(wp_nav_menu( $args ), \'<a><span><img>\' );
如何筛选菜单项标题文本并使
<span>
在它之前显示?
最合适的回答,由SO网友:joshmoto 整理而成
您就快到了,请参阅下面代码中的注释。。。
function wp3456789_wp_nav_menu_objects( $items, $args ) {
foreach( $items as &$item ) {
$image = get_field(\'icon\', $item);
if( $image ) {
// Your original code which appends html string to current $item->title
//$item->title .= \'<span class="inline-img\' . $item->class . \'"><img class="style-svg" src="\' . $image[\'url\'] . \'" width="" height="" alt="\' . $image[\'alt\'] . \'" /></span>\';
// To prepend your html to title simply override $item->title with new value
// and include $item->title at the end of your html string value...
$item->title = \'<span class="inline-img \' . $item->class . \'"><img class="style-svg" src="\' . $image[\'url\'] . \'" width="" height="" alt="\' . $image[\'alt\'] . \'" /></span> \' . $item->title;
}
}
return $items;
}
add_filter(\'wp_nav_menu_objects\', \'wp3456789_wp_nav_menu_objects\', 10, 2);
虽然你也应该注意到
$item->class
所有物
有一个$item->classes
属性,该属性是数组。你需要implode()
数组转换为字符串,请参见下面代码中的示例和注释。。。
function wp3456789_wp_nav_menu_objects( $items, $args ) {
foreach( $items as &$item ) {
$image = get_field(\'icon\', $item);
if( $image ) {
// if $item->classes is array then implode array values into string
$classes = is_array($item->classes) ? implode(" ", $item->classes) : \'\';
// prepend span and image to $item->title
$item->title = \'<span class="inline-img \' . $classes . \'"><img class="style-svg" src="\' . $image[\'url\'] . \'" width="" height="" alt="\' . $image[\'alt\'] . \'" /></span> \' . $item->title;
}
}
return $items;
}
add_filter(\'wp_nav_menu_objects\', \'wp3456789_wp_nav_menu_objects\', 10, 2);