P
P
PiVirus2020-06-20 09:38:11
WordPress
PiVirus, 2020-06-20 09:38:11

Show page images in wordpress menu without plugin?

Good time! There is a menu consisting of pages. Images have been added to the pages. I want to display images of these pages in the menu without a plugin. I do all operations in function.php I get pictures like this:

function get_post_img () {
  $locations = get_nav_menu_locations();
  $items = wp_get_nav_menu_items( $locations['menu-main'] );		
    foreach ( $items as $key => $menu_item ) {
      $post_url = $menu_item->url;
      $post_id = url_to_postid($post_url);			
      $post_img = get_the_post_thumbnail($post_id);
      return $result = ''. $post_img . '';
    }	
}

And in the same place I try to display them in the menu
add_filter( 'wp_nav_menu_args', 'add_item_img' );
function add_item_img( $args='' ){
    $args['link_before'] = get_post_img ();
    return $args;
}

But I ran into a problem, link_before type arguments do not know how to work with variables and add the same element for everyone. In this case, the code takes the image of the first page in the list and adds it to all menu items. I understand that somehow through the walker, at the stage of forming the menu elements, you need to add pictures using the get_post_img () function, but I can’t catch up with how.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2020-06-20
@azerphoenix

Look towards Walker.
For more customization of the menu, you need a walker
https://wp-kama.ru/function/walker
https://misha.blog/wordpress/nav-menu-walkers.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question