以下是两个示例PHP函数:
function myimage1() {
global $post;
$attachment_id = get_post_meta($post->ID, 'f1image', $single = true);
$myimage1 = wp_get_attachment_image( $attachment_id, thumbnail );
return $myimage1;
}
(我称之为:<?php echo myimage1(); ?>
)
和
function myimage2() {
global $post;
$attachment_id = get_post_meta($post->ID, 'f1image', $single = true);
$myimage2 = wp_get_attachment_image( $attachment_id, medium );
return $myimage2;
}
(我称之为:<?php echo myimage2(); ?>
)
如您所见,两者都有一个共同变量$attachment_id
。这两个函数都是非常相关的,只是我不知道如何将它们组合在一起,或者如何从组合函数中调用它们。
PS:我不懂PHP,我的术语可能有点模糊。在这种情况下,请随时纠正我。
答案 0 :(得分:2)
function myimage($level) {
global $post;
$attachment_id = get_post_meta($post->ID, 'f1image', true);
$myimage = wp_get_attachment_image( $attachment_id, $level );
return $myimage;
}
myimage("medium");
myimage("thumbnail");
答案 1 :(得分:0)
OOP正是为了满足这种需求。两个函数(方法)使用相同的类变量。
<?php
class A {
public $attachment_id;
private function wp_get_attachment_image() {
// place your wp_get_attachment_image() function content here
}
public function myimage1() {
$myimage1 = $this->wp_get_attachment_image($this->attachment_id, medium);
return $myimage1;
}
public function myimage2() {
$myimage2 = $this->wp_get_attachment_image($this->attachment_id, medium);
return $myimage2;
}
}
$a = new A;
$a->attachment_id = $a->get_post_meta($post->ID, 'f1image', $single = true);
$a->myimage1();
$a->myimage2();
?>