WordPress FAQ

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?

See How to Send a Notification with WordPress.

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:

setTimeout(function(){
  console.log("about to initialize OneSignal"); 
  window.OneSignal = window.OneSignal || [];
  window.OneSignal.push(function() {
    window.OneSignal.init(window._oneSignalInitOptions);
    OneSignal.showSlidedownPrompt();
  });
}, 10000);

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

🚧

Does not require any changes in the OneSignal.com dashboard

Currently this requires adding code directly to the site.

1. Switch to a manual initialization of OneSignal

Select "Disable OneSignal initialization" at the bottom of the plugin.

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.

// Delay Only Example
// (see next tab for an example of Delay with Categories)

setTimeout(function(){
  console.log("about to initialize OneSignal"); 
  window.addEventListener('load', function() {
    window._oneSignalInitOptions.promptOptions = {
      slidedown: {
        prompts: [
          {
            type: "push",
            autoPrompt: true,
            text: {
              actionMessage: "Your Custom Action Message",   
              acceptButtonText: "Custom Yes button",
              cancelButtonText: "Custom No button",
            },
            delay: {
              timeDelay: 20,
              pageViews: 3,
            }
          }
        ]
      }
    }
    window.OneSignal = window.OneSignal || [];
    window.OneSignal.push(function() {
      window.OneSignal.init(window._oneSignalInitOptions);
    });
  });
}, 10000);
setTimeout(function(){
  console.log("about to initialize OneSignal"); 
  window.addEventListener('load', function() {
    window._oneSignalInitOptions.promptOptions = {
      slidedown: {
        prompts: [
          {
            type: "category",
            autoPrompt: true,
            text: {
              actionMessage: "Your Custom Action Message",   
              acceptButtonText: "Custom Yes button",
              cancelButtonText: "Custom No button",
              /* CATEGORY SLIDEDOWN SPECIFIC TEXT */
              negativeUpdateButton:"Cancel",
              positiveUpdateButton:"Save Preferences",
              updateMessage: "Update your push notification subscription preferences.",
            },
            delay: {
              timeDelay: 20,
              pageViews: 3,
            },
            categories: [
              {
                tag: "politics",
                label: "Politics",
              },
              {
                tag: "usa_news",
                label: "USA News",
              },
              {
                tag: "world_news",
                label: "World News",
              },
              {
                tag: "culture",
                label: "Culture",
              }
            ]
          }
        ]
      }
    }
    window.OneSignal = window.OneSignal || [];
    window.OneSignal.push(function() {
      window.OneSignal.init(window._oneSignalInitOptions);
    });
  });
}, 10000);

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.


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.

Setup WordPress and Non-WordPress site

Select our Custom Code Setup in the OneSignal dashboard. This will be used for both the WordPress and non-wordpress parts of your site.

The WordPress plugin already adds the OneSignal Service Worker files needed but for non-wordpress pages, you still need to add the OneSignal init code.

Use the following code on your site, make sure to replace with your OneSignal app id used in the WordPress plugin:

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
   var OneSignal = window.OneSignal || [];
    var initConfig = {
        appId: "REPLACE_WITH_YOUR_APP_ID_IN_WORDPRESS_PLUGIN",
        notifyButton: {
            enable: true
        },
    };
    OneSignal.push(function () {
        OneSignal.SERVICE_WORKER_PARAM = { scope: '/wp-content/plugins/onesignal-free-web-push-notifications/sdk_files/' };
        OneSignal.SERVICE_WORKER_PATH = 'wp-content/plugins/onesignal-free-web-push-notifications/sdk_files/OneSignalSDKWorker.js'
        OneSignal.SERVICE_WORKER_UPDATER_PATH = 'wp-content/plugins/onesignal-free-web-push-notifications/sdk_files/OneSignalSDKUpdaterWorker.js'
        OneSignal.init(initConfig);
    });
</script>

Did this page help you?