Skip to content

Instantly share code, notes, and snippets.

@castroalves
Created January 23, 2020 18:25
Show Gist options
  • Save castroalves/0fbb4d3d11ee471c644f81e92daebd09 to your computer and use it in GitHub Desktop.
Save castroalves/0fbb4d3d11ee471c644f81e92daebd09 to your computer and use it in GitHub Desktop.
/**
* Book CPT for testing purposes
*/
function cpt_book()
{
register_post_type(
'cpt_book',
array(
'labels' => array(
'name' => __('Books'),
'singular_name' => __('Book'),
),
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'books' )
)
);
}
add_action('init', 'cpt_book');
/**
* Get all posts for the current user
*/
function cadu_get_current_user_posts()
{
$userId = get_current_user_id();
$userPosts = new WP_Query([
'post_type' => 'cpt_book',
'post_status' => 'publish',
'author' => $userId
]);
return (int) $userPosts->found_posts;
}
/**
* Remove Add New Book Submenu if user has more than one book published
*/
function cadu_remove_admin_menu()
{
$foundPosts = cadu_get_current_user_posts();
if ($foundPosts >= 1) {
remove_submenu_page('edit.php?post_type=cpt_book','post-new.php?post_type=cpt_book');
}
}
add_action( 'admin_menu', 'cadu_remove_admin_menu' );
/**
* Remove Add New Button if user has more than one book published
*/
function cadu_remove_add_new_button()
{
global $current_screen;
$foundPosts = cadu_get_current_user_posts();
if (
($current_screen->id === 'edit-cpt_book' || $current_screen->id === 'cpt_book')
&& $foundPosts >= 1
) {
echo '<style>
.wrap .wp-heading-inline+.page-title-action { display: none; }
</style>';
}
}
add_action( 'admin_head', 'cadu_remove_add_new_button' );
/**
* Remove Add New Book if user has more than one book published
*/
function cadu_remove_admin_bar_links() {
global $wp_admin_bar;
$foundPosts = cadu_get_current_user_posts();
if ($foundPosts >= 1) {
$wp_admin_bar->remove_menu('new-cpt_book');
}
}
add_action( 'wp_before_admin_bar_render', 'cadu_remove_admin_bar_links' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment