I'm having trouble preventing the edit page link from appearing in the admin bar on the frontend when non-super admin users view hidden pages. I have several functions that are supposed to remove the edit link and adjust the user’s capabilities for these pages, but the link still shows up.
Below are the relevant parts of my code that handle removing the edit link and related functionality:
// Remove edit-related nodes from the admin bar on hidden pages.
public function remove_edit_button_for_hidden_pages($wp_admin_bar) {
// Bail early if user is super admin or feature is disabled.
if ($this->is_super_admin() || !$this->is_enabled()) {
return;
}
// Get current post ID.
$post_id = get_queried_object_id();
if (!$post_id || get_post_type($post_id) !== 'page') {
return;
}
// Check if the page is hidden.
$hidden_pages = $this->get_hidden_pages();
if (in_array($post_id, $hidden_pages)) {
$wp_admin_bar->remove_node('edit');
$wp_admin_bar->remove_node('customize');
$wp_admin_bar->remove_node('edit-frontend');
$wp_admin_bar->remove_node('site-editor');
$wp_admin_bar->remove_node('edit-site');
$wp_admin_bar->remove_node('edit-page');
$wp_admin_bar->remove_node('edit-post');
}
}
// Backup removal of edit nodes later in the process.
public function remove_edit_menu_late() {
global $wp_admin_bar;
if ($this->is_super_admin() || !$this->is_enabled()) {
return;
}
$post_id = get_queried_object_id();
if (!$post_id || get_post_type($post_id) !== 'page') {
return;
}
$hidden_pages = $this->get_hidden_pages();
if (in_array($post_id, $hidden_pages)) {
$wp_admin_bar->remove_node('edit');
$wp_admin_bar->remove_node('edit-frontend');
$wp_admin_bar->remove_node('customize');
}
}
// Filter to remove the edit link for hidden pages.
public function remove_hidden_page_edit_link($link, $post_id, $context) {
if (!$this->is_enabled() || $this->is_super_admin()) {
return $link;
}
if (get_post_type($post_id) !== 'page') {
return $link;
}
$hidden_pages = $this->get_hidden_pages();
if (in_array($post_id, $hidden_pages)) {
return ''; // Prevent the edit link from being generated.
}
return $link;
}
// Adjust user capabilities for hidden pages.
public function control_edit_page_cap($allcaps, $caps, $args, $user) {
if (!$this->is_enabled() || $this->is_super_admin()) {
return $allcaps;
}
// Check if we're handling edit capabilities.
if (!isset($args[0]) || !in_array($args[0], array('edit_post', 'edit_page'))) {
return $allcaps;
}
// Get the post ID.
$post_id = isset($args[2]) ? $args[2] : 0;
if (!$post_id) {
return $allcaps;
}
// Check if this is a page.
$post = get_post($post_id);
if (!$post || $post->post_type !== 'page') {
return $allcaps;
}
// If the page is hidden, remove editing capabilities.
$hidden_pages = $this->get_hidden_pages();
if (in_array($post_id, $hidden_pages)) {
unset($allcaps['edit_post']);
unset($allcaps['edit_pages']);
unset($allcaps['edit_others_pages']);
unset($allcaps['edit_published_pages']);
unset($allcaps['edit_private_pages']);
}
return $allcaps;
}