0

编辑:我已经设法让这个类工作并且我已经更新了正确的代码。我不想在值的末尾使用 [0]。有什么办法可以改进这段代码?

此类检索特定帖子的所有自定义键。目前我用它来关联图像,我在我的帖子中定义了三个键:'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");
4

1 回答 1

1

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

get_post_custom_values($key, $post_id)

因此,如果您想获得“正常”图像,则可以(在循环中)

echo get_post_custom_values('normal', get_the_ID())

如果您需要更多信息,这里是Wordpress codex中的链接

于 2009-06-09T07:35:20.523 回答