wp_schedule_single_event()


WordPressのwp_schedule_single_event()関数は、指定された時間に一度だけ実行されるスケジュールイベントを登録するために使用されます。

シンタックス

wp_schedule_single_event( int $timestamp, string $hook, array $args = array() );

引数の説明

  • $timestamp (int) — イベントが実行されるUNIXタイムスタンプ。
  • $hook (string) — 実行されるアクションフック名。
  • $args (array) — アクションフックに渡される追加の引数。省略可能。

使用例

例1. 5分後にイベントをスケジュールする

以下のコードは、現在の時間から5分後に「my_custom_hook」をスケジュールします。

wp_schedule_single_event( time() + 300, 'my_custom_hook' );

例2. 引数付きでイベントをスケジュールする

以下のコードは、カスタムフック「my_custom_hook」に引数を渡します。

wp_schedule_single_event( time() + 600, 'my_custom_hook', array( 'post_id' => get_the_ID() ) );

例3. イベントの存在を確認する

以下のコードは、指定したフックが既にスケジュールされているかを確認します。

if ( ! wp_next_scheduled( 'my_custom_hook' ) ) {
    wp_schedule_single_event( time() + 3600, 'my_custom_hook' );
}

例4. スケジュールされたイベントを削除する

以下のコードは、「my_custom_hook」のスケジュールをキャンセルします。

$timestamp = wp_next_scheduled( 'my_custom_hook' );
if ( $timestamp ) {
    wp_unschedule_event( $timestamp, 'my_custom_hook' );
}

例5. スケジュールされたフックの処理

以下のコードは、スケジュールされたフックに関連付けられたアクションを登録します。

add_action( 'my_custom_hook', function() {
    error_log( 'カスタムフックが実行されました!' );
} );

注意事項

  • wp_schedule_single_event()でスケジュールされたイベントは、指定された時間に一度だけ実行されます。
  • スケジュールイベントは、Cronシステムに依存しているため、トリガーされるにはサイトへの訪問が必要です。

関連機能: