我正在尝试制作一个wordpress插件,为客户生成一个唯一的订单ID。我正在做如下,但它没有返回值。我的代码如下所示。
class abc {
function __construct() {
add_action( 'publish_wpcf7s', array($this, 'send_mails_on_publish' ), 10, 2);
}
function setID() {
global $id;
$a = md5(time());
echo $id = substr($a,0,8);
}
function send_mails_on_publish($post)
{
global $post;
global $id;
$price = get_post_meta( $post->ID, 'quote_price', true );
$to = get_post_meta( $post->ID, 'email', true );
$subject ="Thank You! Please Pay $price Us For Order No. $id";
$message ="message";
$headers[] = "Disposition-Notification-To: $sender_email\n";
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'From: Example ' . "\r\n";
wp_mail( $to, $subject, $body, $headers );
}
}
答案 0 :(得分:3)
定义$id
属性,初始化然后在$this
class abc {
private $id;
function setID() {
$a = md5(time());
$this->$id = substr($a,0,8);
}
function send_mails_on_publish($post) {
// use `$this->id` instead of `id`
}
}
如果您希望每次创建类实例时都自动生成id
属性,只需将其放在__construct()
方法
function __construct() {
$this->setID();
}
答案 1 :(得分:1)
你在哪里打电话给setID()
?无论如何,这段代码真的很有气味。
检查一下:
class abc {
private $id = 0;
private $post;
function __construct() {
add_action('publish_wpcf7s', array($this, 'send_mails_on_publish'), 10, 2);
}
function getId() {
return $this->id;
}
function getPost() {
return $this->post;
}
function setId() {
$a = md5(time());
$this->id = substr($a, 0, 8);
}
function setPost($post) {
$this->post = $post;
}
function send_mails_on_publish() {
//do whatever you want.
$price = get_post_meta($this->post->ID, 'quote_price', true);
$to = get_post_meta($this->post->ID, 'email', true);
$subject = "Thank You! Please Pay $price Us For Order No. $this->id";
//.....
// do whatever you want
}
}
当你想要使用它时:
$Abc = new abc();
$Abc->setId();
$Abc->setPost($post);
另一种方法是,如果您将$post
作为参数传递给构建对象,并在那里设置$this->post
。在这种情况下,您不需要setPost
方法,但如果您想要更改它,可以保留它,但这也不是一个好的设计。