From 0de6a71435c3690c94024fc6e2b497cb19e7f446 Mon Sep 17 00:00:00 2001 From: Jakub Szajna Date: Mon, 28 Jan 2019 11:58:34 +0100 Subject: [PATCH] Allow Post::get_field method to accept default value returned when field is empty. --- .../chisel-starter-theme/Chisel/Post.php | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/generators/wp/templates/chisel-starter-theme/Chisel/Post.php b/generators/wp/templates/chisel-starter-theme/Chisel/Post.php index 9b9cdcad..a28d7611 100644 --- a/generators/wp/templates/chisel-starter-theme/Chisel/Post.php +++ b/generators/wp/templates/chisel-starter-theme/Chisel/Post.php @@ -49,15 +49,20 @@ protected function prepareFakePost( $fields ) { * Overrides get_field function to use fake meta when provided. * * @param $field_name + * @param $default_value mixed Default value if field is empty * * @return mixed */ - public function get_field( $field_name ) { + public function get_field( $field_name, $default_value = null ) { + $value = null; if ( $this->fakeFields && isset( $this->fakeFields[ $field_name ] ) ) { - return $this->fakeFields[ $field_name ]; + $value = $this->fakeFields[ $field_name ]; + } else { + $value = $this->_get_field( $field_name ); + $value = $this->convert( $value, get_class( $this ) ); } - return parent::get_field( $field_name ); + return $value ? $value : $default_value; } /** @@ -69,4 +74,29 @@ public function get_field( $field_name ) { public static function overrideTimberPostClass() { return '\Chisel\Post'; } + + /** + * @param string $field_name + * + * @return mixed + */ + private function _get_field( $field_name ) { + if ( $rd = $this->get_revised_data_from_method( 'get_field', $field_name ) ) { + return $rd; + } + $value = apply_filters( 'timber_post_get_meta_field_pre', null, $this->ID, $field_name, $this ); + if ( $value === null ) { + $value = get_post_meta( $this->ID, $field_name ); + if ( is_array( $value ) && count( $value ) == 1 ) { + $value = $value[0]; + } + if ( is_array( $value ) && count( $value ) == 0 ) { + $value = null; + } + } + $value = apply_filters( 'timber_post_get_meta_field', $value, $this->ID, $field_name, $this ); + $value = $this->convert( $value, get_class( $this ) ); + + return $value; + } }