php - wordpress admin panel, how to prevent users from deleting categories?

I'm trying to remove, hide or disable "Delete" button out of category editing section Code i've tried. No luck. Any ideas?

add_action('admin_head', 'hide_category_buttons');
function hide_category_buttons() {
  echo '<style>
    .taxonomy-category tr:hover .row-actions {
        visibility: hidden;
    }
  </style>';
}

enter image description here

Answer

Solution:

I'm trying to remove, hide or disable "Delete" button out of category editing section Code i've tried. No luck. Any ideas?

The following code should do what you want:

  • "Delete" button, hidden and blocked on post taxonomy category AND it's edit page.
  • "Delete" button, hidden and blocked on post taxonomy tags AND it's edit page.

I've also added a conditional statement regarding the user capability. If a user can edit a post, he won't be concerned by the our restriction.

You can learn more about the current_user_can() function @ https://developer.wordpress.org/reference/functions/current_user_can/

Everything as been tested on my end and it's working.

<?php
add_action( 'init', 'admin_restriction' );
function admin_restriction() {
  if ( is_admin() && strpos( $_SERVER[ 'REQUEST_URI' ], 'edit-tags.php?taxonomy=category' ) || strpos( $_SERVER[ 'REQUEST_URI' ], 'term.php?taxonomy=category' ) || strpos( $_SERVER[ 'REQUEST_URI' ], 'edit-tags.php?taxonomy=post_tag' ) || strpos( $_SERVER[ 'REQUEST_URI' ], 'term.php?taxonomy=post_tag' ) ) {
    if ( ! current_user_can( 'edit_post' ) ) { //Define use capability here
      add_action( 'admin_head', 'admin_scripts' );
      function admin_scripts() {
        echo "<style type='text/css'>
        .delete {
          display: none;
          visibility: hidden; }
        </style>";
        echo "<script type='text/javascript'>
        jQuery( document ).ready( function($) {
          $( '.delete-tag' ).click( false ); } );
        </script>";
      };
    };
  };
}; ?>

Source