首页 > 解决方案 > WordPress 在我发布自定义帖子类型时发送通知

问题描述

当我在 WordPress 中发布名为“通知”的 CPT 时,我想发送通知网络推送。

$data = array(
'app_id' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'data' => array(
    'foo' => 'bar'
),
'headings' => array(
    'en' => 'Test Notifications API'
),
'contents' => array(
    'en' => 'Test Notifications API'
),
'url' => 'PAGE URL',
'include_player_ids' => [
  'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
]);

$data_string = json_encode($data);

$ch = curl_init('https://onesignal.com/api/v1/notifications/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);

我想在发布我的 CPT“通知”时发送 $result。

感谢帮助。

标签: wordpresshook

解决方案


您需要将其与某些操作挂钩,例如save_postortransition_post_status

function my_published_notification( $new, $old, $post ) {
     if ( $new === 'publish' && $new !== $old ) {
           // put whatever you want to do here
     }
}

add_action( 'transition_post_status', 'my_published_notification', 10, 3 );

对于 CPT,您还有一些自定义挂钩选项,例如 likesave_*publish_*where *is myCPTname

add_action( 'publish_myCPTname', 'my_published_notification', 10, 2 );

查看更多信息 ok 钩子和操作以获取更多详细信息。


推荐阅读