尝试创建一个用于在Wordpress中关联图像的类

时间:2009-06-08 20:33:32

标签: php wordpress key

修改: 我设法使这个类工作,我已经更新了正确的代码。 我不想在值的末尾使用[0]。我可以用任何方式改进这段代码吗?

此类检索特定帖子的所有自定义键。目前我用它来关联图像,我在帖子中定义了thre键:'related_image','related_image_wide'和'image_alt_text。

编辑2: 我终于设法以我想要的方式获得价值。我希望这对任何发现这一点的人都有用。代码已更新。

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 inside The Loop
$article = new article($post);
echo $article->relatedImage("normal");

1 个答案:

答案 0 :(得分:1)

实际上有一个内置的Wordpress功能可以帮助你解决这个问题。

get_post_custom_values($key, $post_id)

所以,如果你想获得'正常'的图像,你会去(在循环中)

echo get_post_custom_values('normal', get_the_ID())

如果您需要更多信息,请参阅Wordpress codex中的链接