You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何隐藏WordPress后台自定义文章类型的「添加新项」按钮?

隐藏WordPress后台自定义文章类型「添加新项」按钮的解决方案

没问题,我给你整理了几个实用的解决方案,帮你搞定这个需求:

方法一:通过权限控制隐藏(推荐)

这种方法不仅会隐藏按钮,还会从根源上禁止用户创建该类型的内容,安全性更高。你可以在主题(或子主题)的functions.php文件末尾添加以下代码,记得把your_custom_post_type替换成你实际的自定义文章类型slug(比如你的自定义类型是“案例”,slug可能是case):

add_filter('register_post_type_args', 'hide_add_new_for_custom_post', 10, 2);
function hide_add_new_for_custom_post($args, $post_type) {
    // 替换为目标自定义文章类型的slug
    $target_type = 'your_custom_post_type';
    
    if ($post_type === $target_type) {
        // 禁用创建新内容的权限
        $args['capabilities']['create_posts'] = 'do_not_allow';
        $args['map_meta_cap'] = true;
    }
    return $args;
}

添加后刷新后台,「添加新项」按钮就会自动消失,而且用户也没法通过其他路径添加该类型的内容。

方法二:直接移除菜单入口

如果只是想单纯隐藏菜单按钮(不限制底层权限),可以用这个方法。同样在functions.php里添加代码:

add_action('admin_menu', 'remove_add_new_menu_item');
function remove_add_new_menu_item() {
    // 替换为你的自定义文章类型slug
    $post_type_slug = 'your_custom_post_type';
    remove_submenu_page(
        'edit.php?post_type=' . $post_type_slug,
        'post-new.php?post_type=' . $post_type_slug
    );
}

注意:这种方法只是隐藏了菜单,用户如果知道直接访问添加页面的URL,还是能进入,所以更推荐第一种方法。

方法三:用插件实现(适合非技术用户)

如果你不想写代码,可以安装权限管理类插件,比如User Role Editor。安装完成后进入插件设置页面,找到对应的用户角色,取消该自定义文章类型的「创建」权限,就能隐藏「添加新项」按钮了。


内容的提问来源于stack exchange,提问作者Ketan

火山引擎 最新活动