views:

46

answers:

1

EDIT: I have managed to get this class working and I have updated the correct code. I would love not to use the [0] at the end of the value. Any way I can improve this code?

This class retrieves all custom keys for a specific post. Currently I use it for relating images and I have defined thre keys in my post: 'related_image', 'related_image_wide' and 'image_alt_text.

EDIT 2: I have finally managed to get the value the way I want it. I hope this can be usefull for anyone who finds this. The code has been updated.

class article {
  private $alternative_text;
  private $custom_fields = array();


  public function __construct($post)
  {
    $val = array();
    $custom_field_keys = get_post_custom_keys();

    foreach ( $custom_field_keys as $key => $value ) 
    {
      // Custom_fields["a"] gets the value of the custom field "a" 
      $val = get_post_custom_values($value);
      $this->custom_fields[$value] = $val[0];
    }

    $this->alternative_text = $this->custom_fields["image_alt_text"];
  }


  public function relatedImage($type)
  {
    // Standard image to be shown with article
    if($type == 'normal')
      return $this->imageURL($this->custom_fields["related_image"]);

    // Wide image to be shown with article.
    if($type == 'wide')
      return $this->imageURL($this->custom_fields["related_image_wide"]);

    // Alternative image. Often used in article listing and not in main article
    if($type == 'alt')
      return $this->imageURL($this->custom_fields["related_image_alternative"]);      
  }

  private function imageURL($imgPath)
  {
    return '<img src="' . get_option('home') . '/wp-content/uploads' . $imgPath .'" alt="' . $this->alternative_text . '" title="' . $this->alternative_text . '" />';
  }

}

This is what I do in my template code:

//This is inside The Loop
$article = new article($post);
echo $article->relatedImage("normal");
+1  A: 

Hello

There is actually a built in Wordpress function that can help you with this.

get_post_custom_values($key, $post_id)

So if you wanted to get the 'normal' image you would go (in the Loop)

echo get_post_custom_values('normal', get_the_ID())

Here is the link in the Wordpress codex if you need more information

Paul Sheldrake
Trust me, that was one of the first things I tried :) But it did not work. But I got it working now.
Steven