I'm trying to send push notification when any of posts, custom post types or pages is published. I'm getting enabled post types from the plugin settings and adding action via foreach
loop in my class __construct
method. The problem is that it only works for posts and not for any of custom post types or pages. Here is my function and action:
foreach ((array)get_option('PushPostTypes') as $postType) {
add_action("publish_{$postType}", array($this, 'doNewPostPush'), 10, 2);
}
public function doNewPostPush($id, $post) {
$pushData = array(
'title' => $post->post_title,
'body' => strip_tags($post->post_content),
'data' => array(
'url' => trailingslashit(get_permalink($id)),
),
);
if (has_post_thumbnail($id)) {
$pushData['image'] = get_the_post_thumbnail_url($id);
}
$this->sendNotification($pushData);
}
get_option('PushPostTypes')
is an array of post types that user choose, for example: array('post', 'page', 'custom_post');
Any idea why it only works for post
and not for pages or custom post types?
Your code worked for me, assuming your
get_option('PushPostTypes')
is working as intended (Obviously I had to mock that).Try a different approach that does not rely on
get_option('PushPostTypes')
to see if you get the same result;Try the
'transition_post_status'
hook that works for all posts without specifically defining them. Put that somewhere just to see if it runs. Do whatever debugging statement that suits you. Then if that works, then move it into Class code and see if that works. I'm debugging by trying to isolate where the first thing goes wrong. Keeping it very simple to get it to work, then gradually adding complexity until it breaks.