我不喜欢再次解析菜单项的想法。作为替代解决方案,我建议在第一次运行时存储描述:
add_filter( \'walker_nav_menu_start_el\', \'wpse_78483_get_current_items_description\', 10, 2 );
/**
* Get nav items description.
*
* @wp-hook walker_nav_menu_start_el
* @param string $item_output
* @param object $item
* @return string
*/
function wpse_78483_get_current_items_description( $item_output = NULL, $item = NULL )
{
static $desc = \'\';
// The function is NOT called during nav menu rendering, but later.
if ( \'walker_nav_menu_start_el\' !== current_filter() )
return $desc;
// The function is called during wp_nav_menu().
// description is set
if ( ! empty ( $item->description )
// and an URL is available
and ! empty ( $item->url )
// and it is the current page
and parse_url( $item->url, PHP_URL_PATH ) === $_SERVER[\'REQUEST_URI\']
)
{
// copy the description into our static internal variable
$desc = $item->description;
// remove this filter, it is not needed anymore
remove_filter( \'walker_nav_menu_start_el\', __FUNCTION__ );
}
// return unchanged item markup
return $item_output;
}
解释该函数有两个功能:
它作为一个过滤器,在wp_nav_menu()
. 在这里,它被调用,直到它到达当前页面。然后将描述存储在$desc
.它充当描述的getter:如果不带参数调用此函数after 导航菜单已呈现,如果有描述,您将获得描述的值缺点是:对于太晚的菜单调用,例如在页脚中,它不起作用<优点:节省时间。
您可以在以后的任何时候通过调用不带参数的函数来获取描述:
print wpse_78483_get_current_items_description();
下面是第二种使用方法:
$desc = wpse_78483_get_current_items_description();
if ( empty ( $desc ) )
{
the_excerpt();
}
else
{
print wpautop( $desc );
}
额外提示:您可以为以下页面启用摘录编辑器框:
add_action( \'wp_loaded\', \'wpse_78483_page_excerpt\' );
function wpse_78483_page_excerpt()
{
add_post_type_support( \'page\', \'excerpt\' );
}