Skip to content

Instantly share code, notes, and snippets.

@jonathanbossenger
Last active November 30, 2024 08:07
Show Gist options
  • Save jonathanbossenger/ec66d2876618e629bc85b21a58fa4153 to your computer and use it in GitHub Desktop.
Save jonathanbossenger/ec66d2876618e629bc85b21a58fa4153 to your computer and use it in GitHub Desktop.
/**
* Get Image URL.
*
* @param integer $id ID of the image.
* @param string $args The image arguments.
*
* @return string The image URL.
*/
function zawp_get_image_url( $id, $args ) {
// If image returned is an array, then return it's 'ID'.
if ( is_array( $id ) ) {
$id = $id['ID'];
}
// perform any additional checks here, based on data passed in the $args array.
// Return an empty string if any of the checks fail.
// Get image source.
$img = wp_get_attachment_image_src( $id, $args['size'] );
// perform any additional checks here, based on the returned img array.
// Return the image URL, or an empty string.
return ! empty( $img ) && is_array( $img ) ? $img[0] : '';
}
/**
* Render image container.
*
* @param array $image_id The image id.
* @param array $args The image arguments.
*/
function render_image_url( $image_id, $args ) {
$img_url = zawp_get_image_url( $image_id, $args );
echo '<div class="featured"><img src="' . esc_url( $img_url ) . '" alt="Featured image"></div>';
}
// how to call the render_image_url function in theme templates
render_image_url( 123, array( 'size' => 'full' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment