I want to add a custom code under the third menu item in my WordPress footer menu. It’s meant to show the latest blogpost under the "Blog" (in this case "Insights") menu-item. I managed to do this with HTML, only now i need to add there the latest posts code (in functions.php). Problems i have are:
1: How do i add the PHP code working in functions.php (it’s working in footer.php)
2: I only want it in the footer menu (‘Secondary’), not the main menu (header menu)
Could anyone help me with this? Thanks in advance.
This is the code i have now:
Functions.php
/* footer extra content in menu */
class Add_Div_Walker extends Walker_Nav_Menu
{
}
function nav_replace_wpse_189788($item_output, $item) {
// var_dump($item_output, $item);
if ('Insights' == $item->title) {
global $my_profile; // no idea what this does?
return '<li class="menu-item"><a href="/customers/bluespar/insights/" class="nav-link">Insights</a>
<div class="insights-footer">Custom code
</div></li>';
}
return $item_output;
}
add_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2);
Footer menu in footer.php:
<?php
wp_nav_menu(array(
'theme_location' => 'secondary',
'container' => 'div',
'container_id' => '',
'container_class' => 'justify-content-end',
'menu_id' => false,
'depth' => 3,
'walker' => new Add_Div_Walker
));
?>
Code to show 5 latest posts (now in footer.php, should be in functions.php?)
<ul>
<?php
$the_query = new WP_Query( 'posts_per_page=5' );
while ($the_query -> have_posts()) : $the_query -> the_post();
?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
wp_reset_postdata();
?>
</ul>
2
Answers
By setting ‘theme_location’ => ‘secondary’, the code only runs for the footer menu, not the main menu. The custom walker class includes the markup for the list of posts, ensuring proper HTML structure.
Update functions.php
Create a custom walker class that outputs the latest posts:
footer.php
The start_lvl and end_lvl methods add the necessary tags for submenus. This ensures that submenus () remain inside the parent
<li>
element.