我有一个简单的静态列表,标记如下,我想打开WordPress菜单:
<ul>
<li><a href="#"><img src="http://placekitten.com/200/300"></a></li>
<li><a href="#"><img src="http://placekitten.com/200/300"></a></li>
<li><a href="#"><img src="http://placekitten.com/200/300"></a></li>
<li><a href="#"><img src="http://placekitten.com/200/300"></a></li>
</ul>
我希望每个列表项都链接到一个特定的帖子,并引入特色图片而不是标题。如果我设置默认WordPress菜单,它的输出如下:
<ul>
<li><a href="post-1/">Blog Post 1</a></li>
<li><a href="post-2/">Blog Post 2</a></li>
<li><a href="post-3/">Blog Post 3</a></li>
<li><a href="post-4/">Blog Post 4</a></li>
</ul>
我将如何改为如下输出:
<ul>
<li><a href="post-1/"><img src="post-1-featured-img.png"></a></li>
<li><a href="post-2/"><img src="post-2-featured-img.png"></a></li>
<li><a href="post-3/"><img src="post-3-featured-img.png"></a></li>
<li><a href="post-4/"><img src="post-4-featured-img.png"></a></li>
</ul>
因此,本质上我只想返回我在WordPress自定义菜单中指定的每篇文章的特征图像,而不是文章标题。
SO网友:Ahmad M
可以通过使用过滤菜单对象来实现此目的wp_nav_menu_objects
滤器
以下示例将用<img>
文章或页面缩略图的标记(如果可用)。它将以名称为的菜单为目标Posts Menu
使用在主题中调用wp_nav_menu(array(\'menu\'=>\'Posts Menu\'))
:
add_filter(\'wp_nav_menu_objects\', \'ad_filter_menu\', 10, 2);
function ad_filter_menu($sorted_menu_objects, $args) {
// check for the right menu to filter
// here we check for the menu with name \'Posts Menu\'
// given that you call it in you theme with:
// wp_nav_menu( array( \'menu\' => \'Posts Menu\' ) );
// if you call the menu using theme_location, eg:
// wp_nav_menu( array( \'theme_location\' => \'top_manu\' ) );
// check for:
// if ($args->theme_location != \'top_menu\')
if ($args->menu != \'Posts Menu\')
return $sorted_menu_objects;
// edit the menu objects
foreach ($sorted_menu_objects as $menu_object) {
// searching for menu items linking to posts or pages
// can add as many post types to the array
if ( in_array($menu_object->object, array(\'post\', \'page\', \'any_post_type\')) ) {
// set the title to the post_thumbnail if available
// thumbnail size is the second parameter of get_the_post_thumbnail()
$menu_object->title = has_post_thumbnail($menu_object->object_id) ? get_the_post_thumbnail($menu_object->object_id, \'thumbnail\') : $menu_object->title;
}
}
return $sorted_menu_objects;
}