如何将自定义帖子类型存档添加到菜单 [英] How to add custom post type archive to menu

查看:33
本文介绍了如何将自定义帖子类型存档添加到菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了数周,但仍然没有找到解决此问题的适当方法.

I have been searching for weeks and I still haven't found a proper solution to this problem.

我正在编写一个 Wordpress 主题.我有一个名为 Works 的自定义帖子类型.我想将我的 Works 档案添加到我的菜单中,并在我访问它们时突出显示它和它的帖子.

I am writing a Wordpress Theme. I have a custom post type called Works. I would like to add my Works archive to my menu and have it as well as it's posts highlighted when I access them.

我可以通过以下链接访问我的档案和帖子

I can access my archive and posts on the following links

作品档案:/works/

作品单篇:/works/postname/

到目前为止,我的解决方案是使用模板名称(工作存档)命名我的 archive-works.php 模板文件.然后使用该模板创建一个空页面并将该页面添加到菜单中.这会突出显示菜单中的存档,但不会突出显示单个帖子.

My solution so fare have been to name my archive-works.php template file with a template name (Work archive). Then create an empty page using that template and adding the page to the menu. This highlights the archive in the menu but not the single posts.

我可以使用自定义链接和一些 javascript 轻松解决此问题,但必须有更好更简洁的方法.

I can easily solve this with a custom link and some javascript but there must be a better and cleaner way.

推荐答案

你可以在你的functions.php中做一个简单的技巧:

You can do a simple trick in your functions.php:

add_filter('nav_menu_css_class', 'current_type_nav_class', 10, 2);
function current_type_nav_class($classes, $item) {
    // Get post_type for this post
    $post_type = get_query_var('post_type');

    // Go to Menus and add a menu class named: {custom-post-type}-menu-item
    // This adds a 'current_page_parent' class to the parent menu item
    if( in_array( $post_type.'-menu-item', $classes ) )
        array_push($classes, 'current_page_parent');

    return $classes;
}

在您的情况下,您只需在管理面板中添加一个带有存档菜单项的 'works-menu-item' 类;

In your case, you just have to add a class 'works-menu-item' with that archive menu item by the admin panel;

这篇关于如何将自定义帖子类型存档添加到菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆