Skip to content

Instantly share code, notes, and snippets.

@rgadon107
Created January 27, 2021 02:03
Show Gist options
  • Save rgadon107/8f3f66b5303ddaeb86908704edde93a6 to your computer and use it in GitHub Desktop.
Save rgadon107/8f3f66b5303ddaeb86908704edde93a6 to your computer and use it in GitHub Desktop.
Solution to Code Challenge 2 from "Refactoring Tweaks Workbook"
/* Code Challenge 2, from “Refactoring Tweaks Workbook” by Tonya Mork ( 2016, LeanPub (https://leanpub.com/littlegreenbookofrefactoringtweaks-workbook) ). */
/***************************************************
*
* Original code to be refactored.
*
**************************************************/
/* This function grabs the custom header from the current theme so that it can be displayed. */
function prefix_get_header_image() {
$theme_slug = prefix_actual_current_theme();
$mods = get_option( “theme_mods_{$theme_slug}” );
if ( isset( $mods[‘header_image’] ) &&
remove-header!= $mods[‘header_image’] &&
random-default-image!= $mods[‘header_image’] &&
random-uploaded-image!= $mods[‘header_image’] ) {
return $mods[‘header_image’];
}
return false;
}
/***************************************************
*
* Refactored Code
*
**************************************************/
/**
* Get custom header image for theme.
*
* Refactored function. Decision logic simplified.
*
* @since 1.0.0
* @return array Header image.
*/
function prefix_get_header_image() {
$theme_slug = prefix_actual_current_theme();
$mods = get_option( “theme_mods_{$theme_slug}” );
if ( ! isset( $mods[‘header_image’] ) || ! has_custom_header_image() ) {
return;
}
return $mods[‘header_image’];
}
/**
* Theme has custom header image.
*
* Conditional check for `$mods['header_image'] array abstracted into separate function.
*
* @since 1.0.0
*
* @return bool|null
*/
function has_custom_header_image() {
if ( $mods[‘header_image’] =remove-header||random-default-image||random-uploaded-image’ ) {
return;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment