OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Support

Wordpress

For Developers
For Marketers

Required For Setup

Installing the WordPress Plugin

Download and install the plugin here.

Please follow the instructions on our WordPress plugin's Setup guide, and ignore our documentation here for SDK installation. The same steps are in our plugin's Setup guide.

About the WordPress Plugin

Our plugin:

  • Outputs a script tag on each of your site's pages to our web SDK with the options you've configured

    You may use any of the web SDK JavaScript APIs documented above to customize the web push experience.

  • Hooks in to WordPress whenever a post is created or modified, and sends a notification based on the settings you've configured.

    See Customizing WordPress Plugin Behavior to learn how to use PHP to control what our plugin hooks into and to modify the notification that gets sent out.


How do I ...?

How do I send a notification when a post is published?

Notifications can be sent for when:

  • A post is created using WordPress's default post editor
  • A post is created using a third-party plugin
  • An RSS feed is updated

For posts created from WordPress's default post editor

Create your post as normal, and then check Send notification on post publish.

If your post is a different post type, you might see "Send notification on forum publish". If you are updating instead of creating, you might see "Send notification on post update". Each of these options should also successfully send a notification on the described action.

For posts created from 3rd party plugins

"Post" post types

Make sure Automatically send a push notification when I publish a post from 3rd party plugins is checked, like shown here:

Custom post types

If your 3rd party plugin is sending custom post types, a notification will not be sent out by default. You must add the custom post type to this textbox (comma separated) to allow our plugin to automatically send out notifications. This is done to prevent accidental spam if a plugin sends many notifications of a custom type.

For RSS feed updates

(no programming experience required)

Zapier is a service that allows you to perform actions when another trigger occurs. OneSignal has a Zapier integration for RSS feed updates.

Please view our OneSignal integration here.

How do I categorize users and send notifications to specific categories of users?

This guide will show you how to tag subscribers with a category or multiple categories and send to all subscribers that matches one or more categories.

This requires JavaScript and PHP coding. If you're not familiar with how to add JavaScript code to your WordPress site, you can use the WordPress plugin CSS & JavaScript Toolbox.

Please read our Tagging Guide to learn what it means to tag users and how you can do this. This will be done in JavaScript from your website. To ask users what categories they'd like to subscribe to, you may need to build a simple dialog for this. We do not provide a built-in dialog to ask users to subscribe to specific categories. The entire implementation is up to you.

You may end up tagging a user who is interested in only sports like:

{sports: 1}

A user who is interested in sports, news, and science, might be tagged like:

{sports: 1, news: 1, science: 1}

As our guide mentions, please note that tag values should be simple strings and integers. Using arrays or hashes as tag values will not allow you to match them correctly, since our tag value comparisons are exact matching (for strings) or comparison matching (for integers only, greater than or less than).

Once users are now categorized, you have to intercept our WordPress plugin's sending code, since notifications are still going to all users. To send the notification to one set of users only, you want to send notifications to only a certain Segment. Please create segments after reading our Segments guide.

Then please read the beginning of Customizing WordPress Plugin Behavior (including the orange Important Note on where to place the code). You will want to use the onesignal_send_notification filter. You can use the code below:

(please modify "PUT YOUR SEGMENT NAME HERE" with the segment name you created above)

<?php
add_filter('onesignal_send_notification', 'onesignal_send_notification_filter', 10, 4);

function onesignal_send_notification_filter($fields, $new_status, $old_status, $post)
{
   // Change which segment the notification goes to
  $fields['included_segments'] = array('PUT YOUR SEGMENT NAME HERE');
  
  return $fields;
}

How do I customize the prompt text or welcome notification?

See Customizing Welcome Notifications, Permission Messages, Subscription Bell.

How do I change the prompt text language?

See Customizing Welcome Notifications, Permission Messages, Subscription Bell.

How do I change the subscription bell text, color, or position?

See Customizing Subscription Bell.

How do I send notifications to my mobile app only?

See Opening web and mobile notifications in the browser and app and Sending notifications only to mobile apps not browsers.

How can the clicked notification be opened in the mobile app instead of the browser?

See Opening web and mobile notifications in the browser and app and Sending notifications only to mobile apps not browsers.

How can I send notifications to both my mobile app and browser?

See Opening web and mobile notifications in the browser and app and Sending notifications to both browsers and mobile apps.

How do I use the article's featured image for my notification icon?

See this image and enable Use the post's featured image for the notification icon.

Note: Your theme must support featured images. Not all themes support featured images (you may want to contact the theme author if you are having trouble with this). Another way to check if your theme supports featured images, is by opening the theme editor (Appearance -> Editor), finding the functions.php file, and search for post-thumbnails. You should see:

add_theme_support( 'post-thumbnails' );

As explained in WordPress's Post Thumbnails documentation. If you do not see this, your theme does not support featured images.

How do I enable the plugin for certain pages only?

We offer two options that can optionally be combined:

  • Initializing OneSignal conditionally from server-sided PHP

    See Customizing WordPress Plugin Behavior and onesignal_initialize_sdk Filter. Using this hook allows server-sided PHP code to determine when to initialize OneSignal.

    This is useful if you want to target pages based on properties that are only available on the server side.

  • Never initialize OneSignal automatically, manually initialize OneSignal on target pages using client-sided JavaScript

    Please visit our WordPress plugin's Configuration page in your WordPress admin area. Scroll down to the bottom and enable "Disable OneSignal initialization".

    When this option is enabled, OneSignal will not be automatically initialized on any page, and you must add JavaScript code to each page to initialize OneSignal.

    This creates a global JavaScript variable on the page window._oneSignalInitOptions that you can use to initialize OneSignal with (see below) any time you choose.

    You can add conditional JavaScript rules to modify when you'd like to initialize OneSignal.

    Initialize OneSignal with:

window.OneSignal = window.OneSignal || [];
/* Why use .push? See: http://stackoverflow.com/a/38466780/555547 */
window.OneSignal.push(function() {
  /* Never call init() more than once. An error will occur. */
  window.OneSignal.init(window._oneSignalInitOptions);
});

How do I delay prompting users?

You will need to add JavaScript code to your site using our JavaScript web SDK API.

  1. Disable the option Automatically prompt new site visitors to subscribe to push notifications.

  2. Find a way to add JavaScript code to your site. If you don't know how to do this, we recommend installing the WordPress plugin CSS & JavaScript Toolbox.

  3. Using our JavaScript web SDK API, call registerForPushNotifications() to prompt your user under your specific conditions. For example:

Delay prompting for X seconds

<!-- data-cfasync: Ignore CloudFlare's Rocket Loader, which may impact the triggering of the DOMContentLoaded event (see: https://goo.gl/CvZewv) -->
<script data-cfasync="false">
  window.OneSignal = window.OneSignal || [];
  
  /* In milliseconds, time to wait before prompting user. This time is relative to right after the user presses <ENTER> on the address bar and navigates to your page */
  var notificationPromptDelay = 30000;
  
  /* Why use .push? See: http://stackoverflow.com/a/38466780/555547 */
  window.OneSignal.push(function() {
    /* Use navigation timing to find out when the page actually loaded instead of using setTimeout() only which can be delayed by script execution */
    var navigationStart = window.performance.timing.navigationStart;

    /* Get current time */
    var timeNow = Date.now();

    /* Prompt the user if enough time has elapsed */
    setTimeout(promptAndSubscribeUser, Math.max(notificationPromptDelay - (timeNow - navigationStart), 0));
  });
  
  function promptAndSubscribeUser() {
    /* Want to trigger different permission messages? See: https://documentation.onesignal.com/docs/permission-requests#section-onesignal-permission-messages */
    window.OneSignal.isPushNotificationsEnabled(function(isEnabled) {
      if (!isEnabled) {        
        window.OneSignal.registerForPushNotifications();
      }
    });
  }
</script>

Prompt after X visits only

<!-- data-cfasync: Ignore CloudFlare's Rocket Loader, which may impact the triggering of the DOMContentLoaded event (see: https://goo.gl/CvZewv) -->
<script data-cfasync="false">
  window.OneSignal = window.OneSignal || [];
  var numVisitsTrigger = 3; /* Number of page visits before prompting user */
  
  /* Why use .push? See: http://stackoverflow.com/a/38466780/555547 */
  window.OneSignal.push(function() {
    var numVisits = new Number(localStorage['numVisitsTrigger'] || 0);
    numVisits += 1;
    localStorage['numVisitsTrigger'] = numVisits;
    if (numVisits >= numVisitsTrigger) {
      promptAndSubscribeUser();
    }
  });
  
  function promptAndSubscribeUser() {
    /* Want to trigger different permission messages? See: https://documentation.onesignal.com/docs/permission-requests#section-onesignal-permission-messages */
    window.OneSignal.isPushNotificationsEnabled(function(isEnabled) {
      if (!isEnabled) {        
        window.OneSignal.registerForPushNotifications();
      }
    });
  }
</script>

Customizing WordPress Plugin Behavior

Advanced Topic · For Developers

Our WordPress plugin comes with some action and filter hooks that allow you to write PHP code to extend our plugin's functionality.

For example, our hooks can be used to:

  • Automatically check or uncheck the meta box checkbox "Send notification on post publish"
    • You can use this to make it easier for content publishes to automatically send notifications for certain kind of posts
  • Always send a notification for certain post
    • (e.g. custom post types)
  • Never send a notification for certain posts
    • You can combine the include/exclude filter
  • Override any notification parameter, add extra parameters, remove extra parameters, and even send multiple notifications using the same call

Where should the code be placed?

Important Note

For all the following example usage calls, you'll have to copy and paste the PHP code into a file that will always be called. The goal is to add the below code to this file so that it will get called when our plugin takes the specified action. We recommend using WordPress' must-use plugins feature to add your code to a file in the special specified directory to ensure your code is not overwritten when our plugin updates or when you update WordPress.

Here's a specific example to modify the title and body. You might created wp-content/mu-plugins/onesignal-filters.php with this PHP code:

<?php
add_filter('onesignal_send_notification', 'onesignal_send_notification_filter', 10, 4);

function onesignal_send_notification_filter($fields, $new_status, $old_status, $post)
{
  $fields['headings'] = array("en" => "English notification title");
  $fields['contents'] = array("en" => "English notification message body");

  return $fields;
}

onesignal_initialize_sdk Filter

Return true to allow our WordPress plugin to automatically initialize our web SDK on the target page, which (if you've configured to do so) will create the SDK widgets like the red subscription button or prompt users to subscribe.

Return false to prevent our WordPress plugin from automatically initializing our web SDK on the target page.

You can customize when you would like the SDK to be initialized by returning true for some pages and false for other pages.

On pages in which you are returning false, our plugin will not automatically initialize our web SDK and you must initialize OneSignal manually on those pages using client-sided JavaScript code on the page. All the configuration options you've set on our WordPress plugin are still outputted to the page, in a variable called window._oneSignalInitOptions. You must then manually initialize OneSignal by calling OneSignal.init(window._oneSignalInitOptions); in the client-sided JavaScript code of the page. You may modify window._oneSignalInitOptions according to our Web SDK init() documentation.

On pages in which you are returning true, the target pages will be automatically initialized (like normal) -- unless you have the option Use my own SDK initialization script enabled in the WordPress Configuration page (near the bottom).

Enabling Use my own SDK initialization script in our plugin's options is equivalent to returning false for all pages; our plugin will not automatically initialize the web SDK on all pages and you must them manually initialize OneSignal in JavaScript on all pages.

<?php
add_filter('onesignal_initialize_sdk', 'onesignal_initialize_sdk_filter', 10, 1);
function onesignal_initialize_sdk_filter($onesignal_settings) {
    // Returning true allow the SDK to initialize normally on the current page
    // Returning false prevents the SDK from initializing automatically on the current page
    return true;
}

onesignal_meta_box_send_notification_checkbox_state Filter

Overrides the state of the meta box checkbox "Send notification on post publish".

<?php
add_filter('onesignal_meta_box_send_notification_checkbox_state', 'filter', 10, 2);
// Available keys for $onesignal_wp_settings: https://github.com/OneSignal/OneSignal-WordPress-Plugin/blob/master/onesignal-settings.php#L5
function filter($post, $onesignal_wp_settings) {
  // Always leave the checkbox "Send notification on <post type> <action> (e.g. post publish)" unchecked
  return false;
}   

onesignal_include_post Filter

Called every time a post's status changes as part of WordPress's transition_post_status.

Returning true will always send a notification for the specified post. Returning false does nothing; it simply passes control back to our main plugin logic. It's important to note returning false does not exclude the post -- that is done in the onesignal_exclude_post filter.

You can use the onesignal_include_post and onesignal_exclude_post filter together. The order of operations is INCLUDE -> EXCLUDE. The onesignal_include_post filter is run first to determine whether a post is included. If a post is not included, the onesignal_exclude_post filter is run next to determine whether this post is excluded. If the post is not excluded, our normal plugin logic runs.

<?php
add_filter('onesignal_include_post', 'onesignal_include_post_filter', 10, 3);
function onesignal_include_post_filter($new_status, $old_status, $post) {
  return false;
}

Using onesignal_include_post Filter to send notifications when a Page is published

Add this inside your functions.php file under the <?php tag

add_filter('onesignal_include_post', 'onesignal_include_post_filter', 10, 3);
function onesignal_include_post_filter($new_status, $old_status, $post) {
	if ($post->post_type == "page" && $new_status == "publish") {
		return true;
	}
}

onesignal_exclude_post Filter

Called every time a post's status changes as part of WordPress's transition_post_status.

Returning true will never send a notification for the specified post. Returning false does nothing; it simply passes control back to our main plugin logic. It's important to note returning false does not include the post -- that is done in the onesignal_include_post filter.

You can use the onesignal_include_post and onesignal_exclude_post filter together. The order of operations is INCLUDE -> EXCLUDE. The onesignal_include_post filter is run first to determine whether a post is included. If a post is not included, the onesignal_exclude_post filter is run next to determine whether this post is excluded. If the post is not excluded, our normal plugin logic runs.

<?php
add_filter('onesignal_exclude_post', 'onesignal_exclude_post_filter', 10, 3);
function onesignal_exclude_post_filter($new_status, $old_status, $post) {
  return false;
}

onesignal_send_notification Filter

Called after all the notification creation parameters have been determined, and right before the notification is actually sent.

You may modify any of the parameters to, for example:

  • Change the notification's title, message, and URL
  • Send the notification to additional platforms (e.g. Android and iOS)
  • Prevent the notification from being sent to certain platforms
  • Schedule the notification to be sent in the future
  • Add action buttons
  • Cancel the notification from being sent

Please see our Create notification docs page for the full parameter list and description of what's accepted in the $fields hash.

<?php
add_filter('onesignal_send_notification', 'onesignal_send_notification_filter', 10, 4);

function onesignal_send_notification_filter($fields, $new_status, $old_status, $post)
{
   // Change the notification's title, message, and URL
  $fields['headings'] = array("en" => "English notification title");
  $fields['contents'] = array("en" => "English notification message body");
  $fields['url'] = 'https://example.com';
  
  // Send to additional platforms (e.g. Android and iOS)
  $fields['isAndroid'] = true;
  $fields['isIos'] = true;
  
  // Prevent the notification from being sent to certain platforms
  $fields['isFirefox'] = false;
  
  // Schedule the notification to be sent in the future
  $fields['send_after'] = "Sept 24 2018 14:00:00 GMT-0700";
  
  // Schedule the notification to be delivered at the specific hour of the destination timezone
  $fields['delayed_option'] = 'timezone';
  $fields['delivery_time_of_day'] = '9:00AM';
  
  // Add web push action buttons (different action buttons are used for Android and iOS)
  $fields['web_buttons'] = array(
    "id" => "like-button",
    "text" => "Like",
    "icon" => "http://i.imgur.com/N8SN8ZS.png",
    "url" => "https://example.com"
  );
  
  // Cancel the notification from being sent
  $fields['do_send_notification'] = false;
  
  return $fields;
}

Opening web and mobile notifications in the browser and app

Advanced Topic · For Developers

If you have web and mobile platforms users, you can send two notifications: the first notification to web browsers and the second notification to mobile phones. The web push notification will open in a web browser and the mobile push notification will open in your app.

For the first notification sent to web push users, send the notification normally without specifically excluding any parameters.

For the second notification sent to mobile users, make sure to exclude the url parameter. If the url parameter is included, a new browser tab will be opened to that URL. Instead, pass data in to the additionalData field (in a custom format your app will be able to parse), and then use the mobile notification opened / notification clicked handler to navigate the user to a section in your app.

Here is an example using native Android. Here is the documentation for the native notificationOpened handler used by the example.

If you're using Cordova, Phonegap, or Ionic, be sure to use the notificationOpened handler from the Cordova, Phonegap, or Ionic section of our docs . On the code example, be sure to click the variant describing how to open a page in your app.

WordPress Users Only

To take advantage of our WordPress plugin doing this for you, you will have to follow some additional instructions below to add a WordPress filter hook.

  1. On our plugin's Configuration page, please disable the option "Send notifications additionally to iOS & Android platforms". This option does not allow customizing the mobile notifications so we have to disable this option first.

  2. You'll have to copy and paste the PHP code into a file that will always be called. The goal is to add the below code to this file so that it will get called when our plugin takes the specified action. We recommend using WordPress' must-use plugins feature to add your code to a file in the special specified directory to ensure your code is not overwritten when our plugin updates or when you update WordPress.

Sending notifications only to mobile apps (not browsers)

<?php
function onesignal_send_notification_filter($fields, $new_status, $old_status, $post)
{
    $fields['isAndroid'] = true;
    $fields['isIos'] = true;
    $fields['isAnyWeb'] = false;
    $fields['isChrome'] = false;
    $fields['data'] = array(
        "myappurl" => $fields['url']
    );
    /* Unset the URL to prevent opening the browser when the notification is clicked */
    unset($fields['url']);
    return $fields;
}

Sending notifications to both browsers and mobile apps

<?php
add_filter('onesignal_send_notification', 'onesignal_send_notification_filter', 10, 4);

function onesignal_send_notification_filter($fields, $new_status, $old_status, $post)
{
    /* Goal: We don't want to modify the original $fields array, because we want the original web push notification to go out unmodified. However, we want to send an additional notification to Android and iOS devices with an additionalData property.
    */
    $fields_dup = $fields;
    $fields_dup['isAndroid'] = true;
    $fields_dup['isIos'] = true;
    $fields_dup['isAnyWeb'] = false;
    $fields_dup['isWP'] = false;
    $fields_dup['isAdm'] = false;
    $fields_dup['isChrome'] = false;
    $fields_dup['data'] = array(
        "myappurl" => $fields['url']
    );
    /* Important to unset the URL to prevent opening the browser when the notification is clicked */
    unset($fields_dup['url']);
    /* Send another notification via cURL */
    $ch = curl_init();
    $onesignal_post_url = "https://onesignal.com/api/v1/notifications";
    /* Hopefully OneSignal::get_onesignal_settings(); can be called outside of the plugin */
    $onesignal_wp_settings = OneSignal::get_onesignal_settings();
    $onesignal_auth_key = $onesignal_wp_settings['app_rest_api_key'];
    curl_setopt($ch, CURLOPT_URL, $onesignal_post_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Basic ' . $onesignal_auth_key
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields_dup));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // Optional: Turn off host verification if SSL errors for local testing
    // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    /* Optional: cURL settings to help log cURL output response
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    curl_setopt($ch, CURLOPT_HTTP200ALIASES, array(400));
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_STDERR, $out);
    */
    $response = curl_exec($ch);
    /* Optional: Log cURL output response
    fclose($out);
    $debug_output = ob_get_clean();
    $curl_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    $curl_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
    onesignal_debug('OneSignal API POST Data:', $fields);
    onesignal_debug('OneSignal API URL:', $curl_effective_url);
    onesignal_debug('OneSignal API Response Status Code:', $curl_http_code);
    if ($curl_http_code != 200) {
    onesignal_debug('cURL Request Time:', $curl_total_time, 'seconds');
    onesignal_debug('cURL Error Number:', curl_errno($ch));
    onesignal_debug('cURL Error Description:', curl_error($ch));
    onesignal_debug('cURL Response:', print_r($response, true));
    onesignal_debug('cURL Verbose Log:', $debug_output);
    }

    */
    curl_close($ch);
    return $fields;
}

Wordpress

For Developers
For Marketers