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    Discussions

WordPress Plugin Questions

Customizing the OneSignal Wordpress plugin

The OneSignal WordPress plugin adds a OneSignal <script> tag to each of your site's pages and loads our Web Push SDK with the options you've configured.

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

Our plugin 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 send a notification when a post is published?

Notifications can be configured to be sent 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 you normally would, 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 successfully send a notification on the described action.

Set checkbox to checked or unchecked by default

You can set your notifications to send automatically in the OneSignal Plugin Settings under Automatic Notification Settings > Automatically send a push notification when I create a post from the WordPress editor.

This setting will make the checkbox unchecked or checked by default on all posts.

Issue: I can't find the checkbox

Newer versions of WordPress (~5.0+) put the OneSignal Push Notifications checkbox under the Document tab on the right-hand side toolbar (the other tab is Block). Make sure to verify the setting you want before publishing or updating your post!

Issue: There were "no recipients"

Perhaps you are attempting to send multiple notifications for the same post in a short period of time. The initial push notification will go through, but subsequent pushes for the same post will be rate-limited to a one-minute interval.

Issue: My push notification is not scheduling

Scheduling from the WordPress scheduler may or may not work depending on if your WordPress theme is blocking our plugin from sending the notification when the post gets published.

If the scheduler does not work, your options would be:

  1. Schedule the notification for the same time as the post from the OneSignal Dashboard or API. See Sending Push Messages and Product Demo Video
  2. Add custom code to the plugin to schedule it. In this example, you will find how the send notification code looks in the onesignal_send_notification filter. The code sample below demonstrates how to change the delivery time on the notification:
// Schedule the notification to be sent in the future
$fields['send_after'] = "Sept 24 2018 14:00:00 GMT-0700";

See our API Delivery Parameters for more information.

  1. You can use the Zapier OneSignal integration to send an automated notification based on a specific trigger.

For Posts Created From 3rd Party Plugins

"Post" Post Types

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

Custom Post Types

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

A list of WooCommerce Custom Post types can be found here: https://docs.woocommerce.com/document/installed-taxonomies-post-types/

Finding The Custom Post Type

When creating the Custom Post Type in the WordPress post editor, you will usually see the custom post_type name within the URL in your browser's address bar.

For example, https://yoursite.com/wp-admin/post-new.php?post_type=this_is_the_custom_post_type_name.

In the above example, the custom post type name within the URL is this_is_the_custom_post_type_name.

You can add that into the "Additional Custom Post Types for Automatic Notifications..." field in the OneSignal WordPress Plugin by separating it from other types by a comma, like this: article,this_is_the_custom_post_type_name

For RSS Feed Updates

Zapier is a 3rd party service that allows you to perform actions when a trigger occurs, such as publishing a new post. OneSignal has a Zapier integration for RSS feed updates. You can see the OneSignal Zapier integration here for more details.


How do I send multiple notifications for the same blog post?

If you wish to send multiple notifications for the same blog post, you can do so by simply opening the post in your Wordpress editor, checking the "Send notification on post publish" checkbox, and clicking "Update" or "Publish." You do not necessarily have to edit the post content to do this.

NOTE: You must wait at least one minute from the last notification event to be able to resend notifications for that particular post.


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

You can tag subscribers in OneSignal with a single category or multiple categories, and send notifications to all subscribers that match one or more of those categories.

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

1. Tag Users In OneSignal With Custom Code

Please read our Tagging Guide to learn what it means to tag users in OneSignal, and how you can do this. 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}

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).

2. Intercept Notification Sending

Once users are categorized, you then have to intercept our WordPress plugin's notification 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.

Create segments for your categories in your OneSignal dashboard after reading our Segments Guide.

Then read the beginning of Customizing WordPress Plugin Behavior. You will want to use the onesignal_send_notification filter within your custom code.

You can use the code snippet below as a starting point (be sure to modify "PUT YOUR SEGMENT NAME HERE" with the segment name you specified in the OneSignal dashboard):

<?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 use the post's featured image for my notification icon?

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). One 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' );

If you do not see this, your theme does not support featured images for posts. For more details on post-thumbnails, see WordPress's Post Thumbnails documentation.

To set the featured image as an icon or a large image, simply modify the following settings in the OneSignal WordPress plugin.

Turn ON icon only: http://imgur.com/a/ujaCn

Turn ON large image only: http://imgur.com/a/pN4G5

Turn Both ON: http://imgur.com/a/XPNYw

Turn Both OFF: http://imgur.com/a/9ZmBL

Once you're done, be sure to click "Save" at the bottom.


How do I restrict the OneSignal WordPress plugin to certain pages?

We offer two options (that can optionally be combined) to enable the OneSignal WordPress plugin to only appear on certain pages.

Initializing OneSignal Conditionally From Server-Side PHP

See Customizing WordPress Plugin Behavior and onesignal_initialize_sdk filter. Using this hook allows server-side 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.

Manually Initializing OneSignal From Client-Side JS

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

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

This creates a global JavaScript variable on the page - window._oneSignalInitOptions - that you can use to initialize OneSignal any time you choose.

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

The following JS snippet initializes OneSignal:

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?

Currently you will need to add some custom Javascript to the site to delay the Slide Prompt or Native Prompt from showing.

1. Disable the Plugin Prompts

Disable the Slide and Native Prompt in the OneSignal Plugin. Make sure these 2 options are turned off and press "Save" at the bottom.

2. Add custom JavaScript code to your site.

If you don't know how to do this, we recommend installing the CSS & JavaScript Toolbox WordPress plugin.

3. Code Examples

The code snippet below demonstrates delaying prompting for X seconds:

<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) {
        // Show Native Prompt (Not recommended)
        //window.OneSignal.showNativePrompt();
        // Show Slide Prompt
        window.OneSignal.showSlidedownPrompt();
      }
    });
  }
</script>

The code snippet below demonstrates delaying prompting for X page visits:

<!-- 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) {        
        // Show Native Prompt (Not recommended)
        //window.OneSignal.showNativePrompt();
        // Show Slide Prompt
        window.OneSignal.showSlidedownPrompt();
      }
    });
  }
</script>

Customizing WordPress Plugin Behavior

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

Hook or Filter Name
Usage
Description

Customizing push notification data

Override any notification parameter, add extra parameters, remove extra parameters, and even send multiple notifications using the same call.

Filter OneSignal's initialization

Customize which pages should initialize OneSignal.

Automatically check or uncheck the Send Push Notification post meta checkbox

Make it easier to automatically send notifications for certain kind of posts.

Customizing sending posts by post type

Enable or disable sending notifications for certain post types.

Where should custom PHP code be placed?

IMPORTANT: 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.

We recommend using WordPress' must-use plugins feature, which allows you to add your code to a specific file and directory that is protected from being overwritten by updates to our plugin or WordPress.

The goal is to add the below code to this file so that it will get called when our plugin takes the specified action.

Here's a PHP code example to modify the title and body using a file called wp-content/mu-plugins/onesignal-filters.php:

<?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 our subscription widgets (like the red subscription bell or slide prompt).

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-side 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-side 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, unless you have the option Use my own SDK initialization script enabled in the OneSignal WordPress Settings page (this setting should be located near the bottom of the page).

Enabling Use my own SDK initialization script in our plugin's options is equivalent to returning false for all pages; our plugin will no longer automatically initialize the web SDK on any pages, and you must then manually initialize OneSignal using JavaScript on all pages where you want to use it.

<?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 "Send notification on post publish" post meta box checkbox.

<?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_send_notification Filter

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

You may modify any of the parameters to:

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

Please see our Create notification documentation for the full parameter list and descriptions 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;
}

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 that returning false does not exclude the post -- that is done in the onesignal_exclude_post filter.

<?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 the onesignal_include_post filter to send notifications when a page/post is published:

<?php
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.

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

Using Include & Exclude Filters Together

You can use the onesignal_include_post and onesignal_exclude_post filter together, or individually. 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.


Sending Web And Mobile Notifications Together With WordPress

If you have both web and mobile platforms configured in your OneSignal dashboard, and you have subscribers on both platforms, you can configure the OneSignal WordPress plugin to send both web and mobile notifications to your subscribers.

The instructions below demonstrate how to configure a link to open a web browser when the web push notification is clicked, and how to open your mobile app when the mobile notification is tapped.
Custom code is required to accomplish these steps.

Method 1. Custom SDK Code Method

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), 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 or Notification Clicked handlers to navigate the user to a section in your app.

Method 2. Custom WordPress Method

To take advantage of using our WordPress plugin to send notifications to both web and mobile subscribers, you will have to add a WordPress filter hook.

  1. On the OneSignal WordPress plugin's Configuration page, disable the option for "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. Add the onesignal_send_notification_filter code (examples below) into a PHP file that will always be called on all of your pages. We recommend using WordPress' must-use plugins feature, which allows you to add your code to a specific file and directory that is protected from being overwritten by updates to our plugin or WordPress.
WordPress Code Placement
  1. Look in your wp-content directory for the mu-plugins directory. If it doesn't exist, create it
  2. Create a file in the mu-plugins directory called "onesignal-mobile-support.php"
  3. Add the code snippet that matches your use case to the file and save it
Sending Notifications To Mobile Devices Only (No 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 Web Browsers And Mobile Devices
<?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'] = true;
        $fields_dup['isWP'] = false;
        $fields_dup['isAdm'] = false;
        $fields_dup['isChrome'] = false;
        // $fields_dup['android_channel_id'] = "<CHANNEL ID UUID HERE>";
        $fields_dup['data'] = array("myappurl" => $fields['url']);
        /* Important to set web_url to support opening through both mobile and browser*/
        $fields_dup['web_url'] = $fields_dup['url'];
        /* Important to unset the URL to prevent opening the browser when the notification is clicked for mobile app users */
        unset($fields_dup['url']);
        $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'];
        $request = array("headers" => array("content-type" => "application/json;charset=utf-8", "Authorization" => "Basic " . $onesignal_auth_key), "body" => json_encode($fields_dup), "timeout" => 60);
        $response = wp_remote_post($onesignal_post_url, $request);
        if (is_wp_error($response) || !is_array($response) || !isset($response['body'])) {
            $status = $response->get_error_code();
            $error_message = $response->get_error_message();
            error_log("There was a " . $status . " error returned from OneSignal when sending to mobile users: " . $error_message);
            return;
        }
        return $fields;
    }

Android Channels

Unless you set a category (or "channel") for Android that gives the notification a higher priority, WordPress notifications to mobile apps will go straight to the shade, and won't display at the top of the screen.

To fix this, you need to set up an Android category through your OneSignal dashboard (under Settings), set it to the desired importance, and then assign the Channel ID to android_channel_id (commented out in the above code snippet).


Why am I seeing "Couldn't load wp.data"?

  • WordPress 5 + Gutenberg: wp.data is necessary for displaying notices (information banners on push notifications and delivery). If it isn't loading in the editor and you are using Gutenberg, there may be a problem with your setup. Please reach out to OneSignal's Support Team if you're seeing this warning.
  • WordPress 4.0: wp.data is not necessary for notices in WordPress 4+ using the regular editor. You can ignore this warning.

Updated 13 days ago

WordPress Plugin Questions


Customizing the OneSignal Wordpress plugin

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.