How to hide Product fields by role

In this example we are going to develop a little plugin to show how to hide fields using user role.

<?php
/*
Plugin Name: TheCartPress Show-Hide Options by role
Plugin URI: http://extend.thecartpress.com/ecommerce-plugins/
Description: Show-Hide Options by role
Version: 1.0
Author: TheCartPress team
Author URI: http://www.thecartpress.com
License: GPL
Parent: thecartpress
*/

/**
 * This file is part of TheCartPress-ShowHideOptions
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class TCPShowHideOptions {
	function __construct() {
		add_action( 'tcp_hide_product_fields', array( &$this, 'tcp_hide_product_fields' ), 99 );
	}
	function tcp_hide_product_fields() {
		if ( ! is_admin() ) return;
		$current_user = wp_get_current_user();
		if ( $current_user->ID > 0 ) {
			foreach( $current_user->roles as $role ) {
				if ( $role == 'merchant' ) : ?>
var fields = [ '#tcp_type', '#tcp_weight', '#tcp_tax_id', '#tcp_initial_units', '#tcp_is_visible'
, '#tcp_hide_buy_button', '#tcp_exclude_range', '#tcp_sku', '#tcp_order', '#tcp_attribute_sets'
, '#tcp_selected_buybutton', '#tcp_stock', '#tcp_initial_stock' ];

for( var i in fields ) {
	jQuery( fields[i] ).parent().parent().hide();
}
				<?php endif;
			}
		}
	}
}

new TCPShowHideOptions();
?>

As you can see the plugin consists, only, of one class, like all TheCartPress project, which only uses an “action” or “hook” to write a few lines of Javascript on the page.

To hide or show fields, you only need to modify the list of “fields“.

To create a plugin based on this code, you need to create a file with this code and save it in your wp-content/plugins folder of your WordPress installation.