在WordPress中,自定义帖子类型(CPT)允许你创建不同于默认"文章"和"页面"的内容类型。有时你可能需要根据特定条件来控制管理界面中的某些功能,比如"添加新内容"按钮。
要实现只在自定义帖子为空时显示"添加新内容"按钮,你可以使用以下方法:
// 在你的主题的functions.php文件或自定义插件中添加以下代码
function conditionally_hide_add_new_button() {
global $post_type, $pagenow;
// 替换'your_custom_post_type'为你的自定义帖子类型名称
$custom_post_type = 'your_custom_post_type';
// 只在编辑页面和特定帖子类型下执行
if ('edit.php' === $pagenow && $post_type === $custom_post_type) {
// 获取该帖子类型的帖子数量
$post_count = wp_count_posts($custom_post_type);
$published_posts = $post_count->publish;
// 如果有已发布的帖子,移除"添加新内容"按钮
if ($published_posts > 0) {
echo '<style>.page-title-action { display: none !important; }</style>';
}
}
}
add_action('admin_head', 'conditionally_hide_add_new_button');
function conditionally_remove_add_new_menu() {
global $submenu, $pagenow;
$custom_post_type = 'your_custom_post_type';
$post_count = wp_count_posts($custom_post_type);
$published_posts = $post_count->publish;
// 如果有已发布的帖子,移除"添加新内容"菜单项
if ($published_posts > 0) {
if (isset($submenu['edit.php?post_type=' . $custom_post_type])) {
foreach ($submenu['edit.php?post_type=' . $custom_post_type] as $index => $item) {
if ($item[2] === 'post-new.php?post_type=' . $custom_post_type) {
unset($submenu['edit.php?post_type=' . $custom_post_type][$index]);
break;
}
}
}
// 也隐藏页面上的按钮
if ('edit.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === $custom_post_type) {
echo '<style>.page-title-action { display: none !important; }</style>';
}
}
}
add_action('admin_menu', 'conditionally_remove_add_new_menu', 999);
这种功能在以下情况下特别有用:
your_custom_post_type
替换为你实际使用的自定义帖子类型名称functions.php
文件或自定义插件中如果需要更严格的控制,可以结合能力检查:
function disable_new_posts() {
$custom_post_type = 'your_custom_post_type';
$post_count = wp_count_posts($custom_post_type);
if ($post_count->publish > 0) {
// 移除添加新内容的能力
$role = get_role('administrator'); // 可以根据需要更改角色
$role->remove_cap('create_' . $custom_post_type);
// 重定向尝试访问添加新内容页面的用户
if (is_admin() && isset($_GET['post_type']) && $_GET['post_type'] === $custom_post_type && isset($_GET['action']) && $_GET['action'] === 'add-new') {
wp_redirect(admin_url('edit.php?post_type=' . $custom_post_type));
exit;
}
}
}
add_action('admin_init', 'disable_new_posts');
这些方法可以根据你的具体需求进行调整和组合使用。
没有搜到相关的文章