1 | <?php |
||
7 | class PostMetaManager |
||
8 | { |
||
9 | /** |
||
10 | * @param string $metaKey |
||
11 | * @return mixed |
||
12 | */ |
||
13 | public function get( $metaKey, array $args = [] ) |
||
14 | { |
||
15 | if( empty( $metaKey ))return; |
||
16 | |||
17 | $args = $this->normalize( $args ); |
||
18 | $metaKey = $this->buildMetaKey( $metaKey, $args['prefix'] ); |
||
19 | $metaValue = get_post_meta( $args['id'], $metaKey, $args['single'] ); |
||
20 | |||
21 | if( is_string( $metaValue )) { |
||
22 | $metaValue = trim( $metaValue ); |
||
23 | } |
||
24 | return empty( $metaValue ) |
||
25 | ? $args['fallback'] |
||
26 | : $metaValue; |
||
27 | } |
||
28 | |||
29 | /** |
||
30 | * @param string $metaKey |
||
31 | * @param string $prefix |
||
32 | * @return string |
||
33 | */ |
||
34 | protected function buildMetaKey( $metaKey, $prefix ) |
||
35 | { |
||
36 | return ( substr( $metaKey, 0, 1 ) == '_' && !empty( $prefix )) |
||
37 | ? sprintf( '_%s%s', rtrim( $prefix, '_' ), $metaKey ) |
||
38 | : $prefix . $metaKey; |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * @return array |
||
43 | */ |
||
44 | protected function normalize( array $args ) |
||
45 | { |
||
46 | $defaults = [ |
||
47 | 'id' => get_the_ID(), |
||
48 | 'fallback' => '', |
||
49 | 'single' => true, |
||
50 | 'prefix' => Application::prefix() ), |
||
|
|||
51 | ]; |
||
52 | return shortcode_atts( $defaults, array_change_key_case( $args )); |
||
53 | } |
||
54 | } |
||
55 |