| 1 |
<?php |
| 2 |
/** |
| 3 |
* Widget utility functions. |
| 4 |
* |
| 5 |
* @package ContentControl |
| 6 |
* @copyright (c) 2023 Code Atlantic LLC. |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace ContentControl\Widgets; |
| 10 |
|
| 11 |
/** |
| 12 |
* Retrieve data for a widget from options table. |
| 13 |
* |
| 14 |
* @param string $widget_id The unique ID of a widget. |
| 15 |
* |
| 16 |
* @return array<string,mixed> The array of widget settings or empty array if none |
| 17 |
*/ |
| 18 |
function get_options( $widget_id ) { |
| 19 |
static $options = []; |
| 20 |
|
| 21 |
// If already loaded, return existing settings. |
| 22 |
if ( ! isset( $options[ $widget_id ] ) ) { |
| 23 |
$split_pos = strrpos( $widget_id, '-' ); |
| 24 |
|
| 25 |
if ( false === $split_pos ) { |
| 26 |
return []; |
| 27 |
} |
| 28 |
|
| 29 |
// Examples: "text-2" will return "text", "recent-post-2" will return "recent-post". |
| 30 |
$basename = substr( $widget_id, 0, $split_pos ); |
| 31 |
|
| 32 |
// Examples: "text-2" will return "2", "recent-post-2" will return "2". |
| 33 |
$index = substr( $widget_id, $split_pos + 1 ); |
| 34 |
|
| 35 |
$widget_settings = \get_option( 'widget_' . $basename ); |
| 36 |
|
| 37 |
if ( isset( $widget_settings[ $index ] ) ) { |
| 38 |
$options[ $widget_id ] = parse_options( $widget_settings[ $index ] ); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
return parse_options( isset( $options[ $widget_id ] ) ? $options[ $widget_id ] : [] ); |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Checks for & adds missing widget options to prevent errors or missing data. |
| 47 |
* |
| 48 |
* @param array<string,mixed> $options Widget options. |
| 49 |
* |
| 50 |
* @return array<string,mixed> |
| 51 |
*/ |
| 52 |
function parse_options( $options = [] ) { |
| 53 |
return wp_parse_args( $options, [ |
| 54 |
'which_users' => '', |
| 55 |
'roles' => [], |
| 56 |
] ); |
| 57 |
} |
| 58 |
|