简体   繁体   English

WordPress-在同一页面上显示某个类别的帖子

[英]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/ . 在该页面上,我显示一个自定义菜单,其中包含指向诸如“书”,“鞋”等类别的链接。每当我单击这些链接/类别之一时,便会带我到相关的类别页面,例如/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") . 我不希望它重定向我,而是将GET值发送到同一页面(“商店”) Then the shop page would take that GET value and display relevant posts. 然后,商店页面将使用该GET值并显示相关帖子。

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. 我会很感激。

Original Answer: 原始答案:

Use wp_get_nav_menu_items : 使用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. wp_get_nav_menu_items返回菜单项数组。 You get several information on the item, like type (post, category, ...), id, title and so on. 您会获得有关该项目的一些信息,例如类型(帖子,类别,...),ID,标题等。 See http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items for a full list of properties. 有关属性的完整列表,请参见http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items

Hope this helps :) 希望这可以帮助 :)

Update: 更新:

Assuming your permalink setting is set to default, the following code will print a modified menu that uses GET. 假设您的永久链接设置为默认设置,则以下代码将打印使用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. 正则表达式可能不是最好的,因为它会忽略其他GET值,而我对它们没有经验。 If your permalink setting is different and every time you change it, you will have to edit the regex. 如果您的永久链接设置不同,并且每次更改时,都必须编辑正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM