Last active
July 3, 2017 06:03
-
-
Save cameronjonesweb/d1faf39854eee14375af38b4f287e371 to your computer and use it in GitHub Desktop.
[WordPress] A helper class to generate a HTML image string from a supplied image class, array or ID. Useful for dealing with images stored in custom fields.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Helper class to generate responsive image HTML from an id or array | |
class cameronjonesweb_generate_image { | |
public $output; | |
function __construct( $image, $size = 'full' ) { | |
if( is_array( $image ) ) { | |
// It's an array | |
if( isset( $image['ID'] ) ) { | |
$this->output .= $this->compile_image( $image['ID'], $size ); | |
} | |
} else if( is_object( $image ) ) { | |
// It's a post object | |
if( isset( $image->ID ) ) { | |
$this->output .= $this->compile_image( $image->ID, $size ); | |
} | |
} else { | |
// We'll assume it's an ID | |
$this->output .= $this->compile_image( $image, $size ); | |
} | |
} | |
private function open_img() { | |
return '<img '; | |
} | |
private function close_img() { | |
return ' />'; | |
} | |
private function get_src( $id, $size = 'full' ) { | |
$src = wp_get_attachment_image_src( $id, $size ); | |
return ' src="' . $src[0] . '" width="' . $src[1] . '" height="' . $src[2] .'"'; | |
} | |
private function get_alt( $id ) { | |
$alt = get_post_meta( $id, '_wp_attachment_image_alt', true ); | |
$title = get_the_title( $id ); | |
return ' alt="' . ( !empty( $alt ) ? $alt : $title ) . '"'; | |
} | |
private function get_class( $id ) { | |
return ' class="wp-image-' . $id . '"'; | |
} | |
private function compile_image( $id, $size ) { | |
$id = intval( $id ); | |
return $id !== 0 ? wp_make_content_images_responsive( $this->open_img() . $this->get_src( $id, $size ) . $this->get_alt( $id ) . $this->get_class( $id ) . $this->close_img() ) : ''; | |
} | |
public function return_image() { | |
return !empty( $this->output ) ? $this->output : false; | |
} | |
public function display_image() { | |
echo !empty( $this->output ) ? $this->output : false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment