Here is sample code using WordPress and PHP to send a push notification to your mobile application using the OneSignal API. Create a free account on https://onesignal.com/ and get your OneSignal AppID and OneSignal RestID keys.
I use the below PHP code in WordPress to send OneSignal push notifications to Xamarin Forms apps using the OneSignal Nuget https://www.nuget.org/packages/Com.OneSignal/
This code will run after every new WordPress POST is created. It grabs the latest post and will send the post Title and Content to the OneSignal API to send a Push Notification.
I add this code to WordPress using the Code Snippets plugin available for free. Alternatively, you can add this code directly to the WordPress Functions.php file if you wanted too.
This code will work on Posts and Custom Posts. Just edit the ‘publish_post’ parameter in the add_action() function to your custom post name:
change: add_action( 'publish_post', 'GetRecentPost'); to: add_action( 'publish_your-custom-post-name', 'GetRecentPost');
add_action( 'publish_post', 'GetRecentPost'); function call_after_post_publish($id, $post) { $authorID = $post['post_author']; /* Post author ID. */ $title = $post['post_title']; //$post->post_title; $content = $post['post_content']; sendPushNotification($title, $content, $authorID); } function GetRecentPost(){ $recent_posts = wp_get_recent_posts(array( 'numberposts' => 1, // Number of recent posts thumbnails to display 'post_status' => 'publish' // Show only the published posts )); foreach( $recent_posts as $post_item ){ call_after_post_publish($post_item['ID'], $post_item); } } function sendPushNotification($title, $content, $id){ $onesignalappid = 'your-onesignalappid'; $onesignalrestapikey = 'your-onesignalrestapikey'; //send using filters $filters = array( array("field" => "tag", "key" => "userid", "relation" => "=", "value" => $id) ); $subtitle = array( "en" => $title //Title for ios 10 or higher ); $headings = array( "en" => $title ); $content = array( "en" => $content //the message to send ); $fields = array( 'app_id' => $onesignalappid, //'included_segments' => array('Subscribed Users'), //uncomment to use segments //'filters' => $filters, //uncomment to use filters 'large_icon' => "ic_launcher_round.png", 'contents' => $content, 'headings' => $headings, 'subtitle' => $subtitle ); $fields = json_encode($fields); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications"); curl_setopt($ch, CURLOPT_HTTPHEADER, array ( 'Content-Type: application/json; charset=utf-8', 'Authorization: Basic ' . $onesignalrestapikey ) ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $response = curl_exec($ch); curl_close($ch); return $response; }