Php 尝试在Wordpress中创建用于关联图像的类
编辑: 我已经设法让这个类工作,我已经更新了正确的代码。 我不希望在值的末尾使用[0]。有什么办法可以改进此代码吗? 此类检索特定post的所有自定义键。目前,我使用它来关联图像,并在我的帖子中定义了三个键:“相关图像”、“相关图像”和“图像替换文本” 编辑2: 我终于以我想要的方式获得了价值。我希望这对任何找到它的人都有用。代码已更新。Php 尝试在Wordpress中创建用于关联图像的类,php,wordpress,key,Php,Wordpress,Key,编辑: 我已经设法让这个类工作,我已经更新了正确的代码。 我不希望在值的末尾使用[0]。有什么办法可以改进此代码吗? 此类检索特定post的所有自定义键。目前,我使用它来关联图像,并在我的帖子中定义了三个键:“相关图像”、“相关图像”和“图像替换文本” 编辑2: 我终于以我想要的方式获得了价值。我希望这对任何找到它的人都有用。代码已更新。 class article { private $alternative_text; private $custom_fields = array()
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 . '" />';
}
}
实际上,有一个内置的Wordpress函数可以帮助您实现这一点
get_post_custom_values($key, $post_id)
因此,如果你想得到“正常”的图像,你会去(在循环中)
这里是“如果您需要更多信息”中的链接相信我,这是我尝试的第一件事:)但它不起作用。但我现在已经开始工作了。
get_post_custom_values($key, $post_id)
echo get_post_custom_values('normal', get_the_ID())