Created
February 18, 2016 01:52
-
-
Save sc0ttkclark/19283a436f7696ceb28a to your computer and use it in GitHub Desktop.
A class you can drop-in to enable readonly text fields that can't be changed, but optionally you can set `'can_edit_capability' => 'manage_options'` to any capability you'd like to restrict editing to. If user has that capability, a basic text field will be used.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Read only text field, optionally allows for specific users to edit | |
* @package Fieldmanager | |
*/ | |
class Fieldmanager_ReadOnly extends Fieldmanager_TextField { | |
/** | |
* The capability a user must have to be able to edit normally | |
* | |
* @var string | |
*/ | |
public $can_edit_capability; | |
/** | |
* {@inheritdoc} | |
*/ | |
public function form_element( $value = NULL ) { | |
// Allow specific users to edit | |
if ( $this->can_user_edit() ) { | |
return parent::form_element( $value ); | |
} | |
return '<code>' . esc_html( $value ) . '</code>'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function presave( $value = NULL, $current_value = array() ) { | |
// Allow specific users to edit | |
if ( $this->can_user_edit() ) { | |
return parent::presave( $value, $current_value ); | |
} | |
// Don't allow changing value | |
return $current_value; | |
} | |
/** | |
* Whether the current user can edit this field | |
* | |
* @return bool | |
*/ | |
public function can_user_edit() { | |
if ( $this->can_edit_capability && is_user_logged_in() && current_user_can( $this->can_edit_capability ) ) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment