問題描述

我試圖安排一個偽 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。