User_Meta.php
96 lines
| 1 | <?php |
| 2 | /** |
| 3 | * WordPress Customize Setting classes |
| 4 | * |
| 5 | * @package Kirki |
| 6 | * @subpackage Modules |
| 7 | * @since 3.0.0 |
| 8 | */ |
| 9 | |
| 10 | namespace Kirki\Util\Setting; |
| 11 | |
| 12 | /** |
| 13 | * Handles saving and sanitizing of user-meta. |
| 14 | * |
| 15 | * @since 3.0.0 |
| 16 | * @see WP_Customize_Setting |
| 17 | */ |
| 18 | class User_Meta extends \WP_Customize_Setting { |
| 19 | |
| 20 | /** |
| 21 | * Type of customize settings. |
| 22 | * |
| 23 | * @access public |
| 24 | * @since 3.0.0 |
| 25 | * @var string |
| 26 | */ |
| 27 | public $type = 'user_meta'; |
| 28 | |
| 29 | /** |
| 30 | * Get the root value for a setting, especially for multidimensional ones. |
| 31 | * |
| 32 | * @access protected |
| 33 | * @since 3.0.0 |
| 34 | * @param mixed $default Value to return if root does not exist. |
| 35 | * @return mixed |
| 36 | */ |
| 37 | protected function get_root_value( $default = null ) { |
| 38 | $id_base = $this->id_data['base']; |
| 39 | |
| 40 | // Get all user-meta. |
| 41 | // We'll use this to check if the value is set or not, |
| 42 | // in order to figure out if we need to return the default value. |
| 43 | $user_meta = get_user_meta( get_current_user_id() ); |
| 44 | |
| 45 | // Get the single meta. |
| 46 | $single_meta = get_user_meta( get_current_user_id(), $id_base, true ); |
| 47 | |
| 48 | if ( isset( $user_meta[ $id_base ] ) ) { |
| 49 | return $single_meta; |
| 50 | } |
| 51 | return $default; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Set the root value for a setting, especially for multidimensional ones. |
| 56 | * |
| 57 | * @access protected |
| 58 | * @since 3.0.0 |
| 59 | * @param mixed $value Value to set as root of multidimensional setting. |
| 60 | * @return bool Whether the multidimensional root was updated successfully. |
| 61 | */ |
| 62 | protected function set_root_value( $value ) { |
| 63 | $id_base = $this->id_data['base']; |
| 64 | |
| 65 | // First delete the current user-meta. |
| 66 | // We're doing this to avoid duplicate entries. |
| 67 | delete_user_meta( get_current_user_id(), $id_base ); |
| 68 | |
| 69 | // Update the user-meta. |
| 70 | return update_user_meta( get_current_user_id(), $id_base, $value ); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Save the value of the setting, using the related API. |
| 75 | * |
| 76 | * @access protected |
| 77 | * @since 3.0.0 |
| 78 | * @param mixed $value The value to update. |
| 79 | * @return bool The result of saving the value. |
| 80 | */ |
| 81 | protected function update( $value ) { |
| 82 | return $this->set_root_value( $value ); |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Fetch the value of the setting. |
| 87 | * |
| 88 | * @access protected |
| 89 | * @since 3.0.0 |
| 90 | * @return mixed The value. |
| 91 | */ |
| 92 | public function value() { |
| 93 | return $this->get_root_value( $this->default ); |
| 94 | } |
| 95 | } |
| 96 |