WordPress – displaying posts from a category on the same page

I have a page named “Shop”. On that page I display a custom menu, which contains links to categories like “Books”, “Shoes” etc. Whenever I click one of those links/categories it takes me to a relevant category page, for example /category/books/.

I do not want it to redirect me to a category page, I want it to display posts on the same page (“Shop”) that the menu item was clicked on. The only problem I have encountered trying to accomplish this, is the fact that I do not know how to change the custom menu behavior. I don’t want it to redirect me, but instead send a GET value to the same page (“Shop”). Then the shop page would take that GET value and display relevant posts.

Read More

I know how to display posts from a category etc. I just don’t know how to change the behavior of the custom menu.

Could anybody help me? I would be grateful.

Related posts

Leave a Reply

1 comment

  1. Original Answer:

    Use wp_get_nav_menu_items:

    $menu_slug = 'YOUR_MENU_SLUG';
    $menu_id = get_nav_menu_locations()[$menu_slug];
    $menu_items = wp_get_nav_menu_items($menu_id);
    
    foreach($menu_items as $item){
        if($item->object == 'category'){
            print('<p>Title: ' . $item->title . '<br>ID: ' . $item->object_id . '</p>');
        }
    }
    

    wp_get_nav_menu_items returns an array of menu items. You get several information on the item, like type (post, category, …), id, title and so on.
    See http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items for a full list of properties.

    Hope this helps 🙂

    Update:

    Assuming your permalink setting is set to default, the following code will print a modified menu that uses GET.

    $menu = wp_nav_menu(array(
        'theme_location'=>'YOUR_MENU_LOCATION',
        'echo'=>0,
    ));
    $new_url = $_SERVER['SCRIPT_NAME'] . '?shop_page=$1';
    $menu = preg_replace('/href="[^"]*cat=(.+)"/', 'href="'.$new_url.'"', $menu);
    print($menu);
    

    The regex may not be the best as it ignores other GET values and I’m not experienced on them. If your permalink setting is different and every time you change it, you will have to edit the regex.