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.

If your 3rd party plugin uses a custom post type, you can leverage our onesignal_meta_box_send_notification_checkbox_state filter to keep this permanently activated.

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](#onesignal_send_notification-filter. The code sample below demonstrates how to change the delivery time on the notification:

    See our API Delivery Parameters for more information.

// Schedule the notification to be sent in the future
$fields['send_after'] = "Sept 24 2018 14:00:00 GMT-0700";
  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

My Custom Post Type is Not Working

Certain post types may lack the necessary meta data our plugin uses to send the push notification.

Using our onesignal_include_post Filter you can add your post_type. OneSignal's WordPress plugin is open source on Github.

Send Push When a Page is Published

See our example code under onesignal_include_post Filter. More details on WordPress Post Types.

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.

You can also follow our guide for setting up the Category Slidedown (look for the Wordpress code example).

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 translate the Prompt?

Please follow the steps for How do I restrict the OneSignal WordPress plugin to certain pages. If you use the option to Manually Initialize OneSignal from Client-Side JS, you can use the "Slide Prompt Example" code and update the text inside "Your Custom Action Message", "Custom Yes button" and "Custom No button" based on the language for that page.

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);
});
window.addEventListener('load', function() {
  window._oneSignalInitOptions.promptOptions = {
    slidedown: {
        enabled: true,
        autoPrompt: true,
        timeDelay: 20,
        pageViews: 3,
        /*Add your custom message inside the quotes*/
        actionMessage: "Your Custom Action Message",   
        acceptButtonText: "Custom Yes button",
        cancelButtonText: "Custom No button",
    }};

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);
});
})

Extra features: Delayed Prompts and Category Slidedown

Currently you will need to add some custom Javascript to the site to delay prompting as well as using the Category Slidedown.

1. Switch to a manual initialization of OneSignal

Select "Disable OneSignal initialization" at the bottom of the plugin and press "Save".

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

3. Add custom JavaScript code to your site.

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

4. Code Examples

Initialize OneSignal manually with the desired delay configuration. For promptOptions, the valid values available are 1) slidedown or 2) native. We recommend using the slidedown.

window.addEventListener('load', function() {
  window._oneSignalInitOptions.promptOptions = {
    slidedown: {
        enabled: true,
        autoPrompt: true,
        timeDelay: 20,
        pageViews: 3,
        actionMessage: "Your Custom Action Message",   
        acceptButtonText: "Custom Yes button",
        cancelButtonText: "Custom No button",
    }};

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);
});
})
window.addEventListener('load', function() {
  window._oneSignalInitOptions.promptOptions = {
    slidedown: {
      autoPrompt: true,
      enabled: true,
      timeDelay: 20,
      pageViews: 3,
      actionMessage: "Your Custom Action Message",   
      acceptButtonText: "Allow",
      cancelButtonText: "Cancel",
      categories: {
        updateMessage: "Would you like to update your notification preferences?",
        positiveUpdateButton: "Howdy, yes",
        negativeUpdateButton: "Cancel",
        tags: [
          {
            tag: "politics",
            label: "Politics",
          },
          {
            tag: "usa_news",
            label: "USA News",
          },
          {
            tag: "world_news",
            label: "World News",
          },
          {
            tag: "culture",
            label: "Culture",
          }
        ]
      }  
    }
  };

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);
});
})

If you see an error, your code snippet may be initializing too early. Make sure to wrap the code with the 'load' event listener function.


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

onesignal_send_notification filter

Customizing push notification data

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

onesignal_initialize_sdk filter

Filter OneSignal's initialization

Customize which pages should initialize OneSignal.

onesignal_meta_box_send_notification_checkbox_state filter

Automatically check or uncheck the Send Push Notification post meta checkbox

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

onesignal_include_post & onesignal_exclude_post filter

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. Show the URL with an in-app browser

Turn on this switch in your OneSignal WordPress plugin:

That will send the notifications to your mobile apps upon publishing a post. Done!

Method 2. Deep Linking

Turn OFF the Send notifications additional to iOS & Android platforms switch. (This option does not allow customizing the mobile notifications, so we have to disable this option first.)

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;
    }

Within your Mobile App's OneSignal Notification Click Handler add code to detect the result.notification.payload.additionalData which should be set to 'myappurl' parameter like shown in our Deep Linking Guide.


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