問題描述
我試圖安排一個偽 cron 工作,在一段時間後使用 WordPress 外掛傳送電子郵件。到目前為止,當我將電子郵件地址和訊息編碼到’email_about_coupon’ 函式中時,我已經能夠使此程式碼執行; 然而,當我嘗試將引數傳送到函式時,電子郵件永遠不會被髮送。透過使用 Cron GUI 外掛 (http://wordpress.org/extend/plugins/cron-view/installation/),我可以看到即使使用引數也可以註冊 cron 作業。我相信我正在做錯誤的事情,不允許在執行時在函式內正確使用引數。這是我有的:
function schedule_email_cron($post_id)
{
// Get the UNIX 30 days from now time
$thirty_days = time() + 60; // (30 * 24 * 60 * 60)
$post = get_post($post_id);
$email = get_the_author_meta('user_email', $post->post_author);
$args = array('email' => $email, 'title' => $post->post_title);
wp_schedule_single_event($thirty_days, 'email_about_coupon_action', $args);
}
add_action('save_post', 'schedule_email_cron', 1, 1);
add_action('email_about_coupon_action', 'email_about_coupon', 1, 1);
function email_about_coupon($args)
{
// Email text
$text = "<html><body><p>Your coupon titled, ".$args['title']." is expiring soon. Please visit <a href="">".get_bloginfo('siteurl')."/registered/</a> ".get_bloginfo('siteurl')."/registered/ to renew your coupon.</p></body></html>";
// Email headers
$headers = array(
'From: '.get_bloginfo('name').' <'.get_bloginfo('admin_email').'>',
"Content-Type: text/html"
);
$h = implode("rn",$headers) . "rn";
// Send email
wp_mail($args['email'], 'Renew Your Coupon Now!', $text, $h);
}
一如以往,非常感謝您的幫助!
最佳解決方案
我認為你在傳遞引數方面有不匹配,以及你期望如何工作。您傳遞引數陣列以排程並期望您的掛鉤函式接收相同的引數陣列。不是這種情況。
Cron 事件由 do_action_ref_array()處理,do_action_ref_array()透過 call_user_func_array()傳遞引數。
所以你的 hooked 函式不接收陣列的引數,它接收到多個引數 – 一個陣列中的每個元素。
所以你需要再次將陣列的陣列包含在陣列中,或者修改你的函式以處理多個引數。請注意,對於信件,您還需要修改 add_action()呼叫,以便傳遞所需數量的引數,而不是僅傳遞一個引數。
次佳解決方案
感謝拉爾斯特,這讓現在更有意義的地獄。所以我更新了這篇文章,詳細闡述了 Rarst 提到的和 upvote 他為這個發光的差異; )
基本上 wp_schedule_single_event 透過變數 arg 將引數傳遞給你的函式,如 in the codex 所示。該變數”args” 必須是一個陣列,因為陣列中的每個值都將對映到回撥函式中的一個引數。
例:
add_action('example_action', 'example', 1, 3);
$args = array ( 2, 1, 3 );
wp_schedule_single_event(time(), 'example_action', $args);
function example($a, $b, $c)
{
}
2 會去 $ a,1 會去 $ b,3 會去 $ c 。然而,透過三個變數只是可能的,因為這一行,
add_action('example_action', 'example', 1, 3);
看看 codex for add_action 你會看到第四個引數,3 是什麼控制有多少個引數傳遞給回撥函式。預設值為 1 。
所以這個例子也有效:
add_action('example_action', 'example');
$args = array ( array( 2, 1, 3 ) );
wp_schedule_single_event(time(), 'example_action', $args);
function example($a)
{
}
所以這裡的陣列 (2,1,3) 被分配給 $ a 。
所以沙丁魚的問題可以透過一行改變來解決,第 7 行,
$args = array('email' => $email, 'title' => $post->post_title);
變成這樣,
$args = array(array('email' => $email, 'title' => $post->post_title));
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。