Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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.
<?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
You can’t perform that action at this time.