UPDATE: Got the class working properly and updated the code below. Still wondering if there’s a way to avoid using [0] at the end of values. Any suggestions to make this cleaner?
I’m working on a class that grabs all custom meta keys for a particular post. Right now I’m using it to handle image relationships and I’ve set up three meta keys: ‘main_image’, ‘banner_image’, and ‘img_description’.
UPDATE 2: Finally got the value extraction working exactly how I wanted. Posting the final code here in case it helps anyone else.
class PostMedia {
private $description_text;
private $meta_data = array();
public function __construct($current_post)
{
$data = array();
$meta_keys = get_post_custom_keys();
foreach ( $meta_keys as $index => $meta_key )
{
// Meta_data["key"] stores the value of custom field "key"
$data = get_post_custom_values($meta_key);
$this->meta_data[$meta_key] = $data[0];
}
$this->description_text = $this->meta_data["img_description"];
}
public function getImage($format)
{
// Default image for post display
if($format == 'standard')
return $this->generateImageTag($this->meta_data["main_image"]);
// Banner image for header display
if($format == 'banner')
return $this->generateImageTag($this->meta_data["banner_image"]);
// Thumbnail image for listings
if($format == 'thumb')
return $this->generateImageTag($this->meta_data["thumbnail_image"]);
}
private function generateImageTag($imagePath)
{
return '<img src="' . get_option('home') . '/wp-content/uploads' . $imagePath .'" alt="' . $this->description_text . '" title="' . $this->description_text . '" />';
}
}
Here’s how I use it in my template:
// Inside The Loop
$media = new PostMedia($post);
echo $media->getImage("standard");