I modified the code to send push notification when new product published.
So, I added hook and changed title, massage, target url, image to get the value dynamically. But It is not working.
In the theme function , I find no error. But
After publishing post. It is showing a critical error. It failed to send push notification.
Help me by finding the fault or recommend me corrections.
add_action( 'transition_post_status', 'send_push_notification', 9999, 3 );
function send_push_notification ( $new_status, $old_status, $post ) {
if ( 'product' === $post->post_type && 'publish' === $new_status && 'publish' !== $old_status ) {
global $product;
$end_point = 'https://api.webpushr.com/v1/notification/send/sid';
$http_header = array(
"Content-Type: Application/Json",
"webpushrKey: "xxxxxxxxxxx",
"webpushrAuthToken: 31669"
);
$req_data = array(
'title' => $product->get_name(),
'message' => 'check out now',
'target_url' => $product->get_permalink(),
'image' => $product->get_image(),
'sid' => '113596298',
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_header );
curl_setopt( $ch, CURLOPT_URL, $end_point );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $req_data ) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $ch );
echo $response;
}
}
2
Answers
I have cleaned your code and fixed some issues, I am not sure with which hook, you’re running this function, but you must check if
$product
is null on an object when you’re running this code. If you’re running it on the backend, you may or may not get$product
in some cases so check that first then debug other issues.You’re missing the $product object here and also not using standard wp_request_post instead of cURL which is a best practice in wordpress.