url_to_postid method in walker_nav navigation menu causing exceptionally high TTFB

Question

I am using the walker class to create my custom mega menu, and using it to display post thumbnails at a menu depth of 2.

It seems using the url_to_postid method seems to be causing a high ttfb of >10s.
I initially thought it was an image size issue but even after compressing the images by 95% i seem to be getting the same ttfb.

When the offending code is removed ttfb drops dramatically to <1s, but the attachment images don’t display.

Is there any other method I can use to get my thumbnails to display in the mega menu without such a massive drop in performance?

Walker.php code:

function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ){

//url_to_post id causing >10s ttfb
$postid = url_to_postid( $item->url );
$thumbnail = get_the_post_thumbnail_url($postid);

   

if ( array_search( 'menu-item-has-children', $item->classes )&& $depth==0 ) {
    
    
    
 $output .= sprintf( "n<li class="topnavitem %s"><a href="https://wordpress.stackexchange.com/questions/393993/%s" class="topnavtext">%s</a> <span class="plus"><i class="fas fa-angle-down"></i></span>n", ( array_search( 'current-menu-item', $item->classes ) || array_search( 'current-page-parent', $item->classes ) ) ? '' : '', $item->url, $item->title );
} 

elseif ( array_search( 'menu-item-has-children', $item->classes )&& $depth==1 ) {
    $output .= sprintf( "n<li class="productsnav %s"><a href="https://wordpress.stackexchange.com/questions/393993/%s" class="productsnavtext">%s</a><span class="sub-plus"><i class="fas fa-angle-down"></i></span>n", ( array_search( 'current-menu-item', $item->classes ) || array_search( 'current-page-parent', $item->classes ) ) ? '' : '', $item->url, $item->title );
} 

 //$thumbnail using url_to_postid being called at a menu depth of 2 

elseif ($depth==2){
    $output .= sprintf( "n<li class="midnavitem %s"><div class="pictext"><img src="https://wordpress.stackexchange.com/questions/393993/%s"/><a href="https://wordpress.stackexchange.com/questions/393993/%s" class="midnavtext$postid">%s</a></div>n", ( array_search( 'current-menu-item', $item->classes) ) ? '' : '', $thumbnail,$item->url, $item->title );
}




else {
    $output .= sprintf( "n<li class="topnavitem %s"><a href="https://wordpress.stackexchange.com/questions/393993/%s" class="topnavtext">%s</a>n", ( array_search( 'current-menu-item', $item->classes) ) ? '' : '', $item->url, $item->title );
}
 }

function start_lvl( &$output, $depth ) {
$indent = str_repeat( "t", $depth );
if ($depth == 0) {
$output .= "n$indent<ul class="nav-level-one" role="submenu">n";
}


    if ($depth == 1) {
    $output .= "n$indent<ul class="nav-level-two" role="subsubmenu">n";
}

}

0
Prateek Pandey 2 weeks 2021-08-31T00:26:17-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse