Blog

Send SMS from WordPress and WooCommerce with a one-file plugin

A new order or a contact form message texts your phone, a finished order texts the customer, and their replies come back to WordPress. One PHP file, your own number, no per-text fee, tested on WooCommerce and Contact Form 7.

Sparetext

10 min read ยท Nov 25, 2026

Here's a small WordPress secret: the "New order" email is often in spam, and sometimes it never left the server at all. A text to your own phone doesn't have that problem, so we wrote a tiny plugin that sends one for every new order and every contact form message.

It's one PHP file, and it goes through Sparetext, which turns the phone you already own into an SMS gateway with a plain API. So the texts leave from your own number, there's no fee per text, and when a customer replies, the reply comes back to you. Everything below ran on 25 November in a real WordPress with WooCommerce and Contact Form 7, against a test copy of Sparetext with a simulated phone.

What the plugin does

  • A new WooCommerce order texts you: New order #1042: USD 24.50 from Ana Lopez. Once per order, whether it's paid or waiting for a bank transfer.
  • A finished order texts the customer, if they gave a phone number at checkout: Hi Ana, your order #1042 from Mesi's Bakery is complete. Thank you!
  • A Contact Form 7 message texts you, before WordPress even tries the email.
  • Replies come back. When someone texts your phone, Sparetext posts it to your site, the plugin checks the signature and emails it to you, once.

The whole file is on GitHub: sparetext-examples/wordpress. It's MIT licensed, so copy it, rename it, change the words. The rest of this post walks through it, because the small decisions in there are the ones that bite later.

What you need

  • A Sparetext account. Free is 1 phone and 300 texts a month, no card.
  • An Android phone with the Sparetext app, paired in the dashboard. An iPhone works too, through Sparetext for Mac (the iPhone guide).
  • An API key from the API keys page.
  • WordPress 6.0 or newer on PHP 7.4 or newer. WooCommerce and Contact Form 7 are optional: each part only runs if its plugin is there.

Install it and put the key in wp-config.php

Copy the sparetext-sms folder into wp-content/plugins/ (or zip it and upload it under Plugins, Add New, Upload Plugin) and activate it. Then add three lines to wp-config.php, above the "That's all, stop editing!" line:

wp-config.php
define('SPARETEXT_API_KEY', 'spt_live_...');      // https://sparetext.dev/keys
define('SPARETEXT_NOTIFY', '+12025550100');       // your number: new orders and form messages
define('SPARETEXT_WEBHOOK_SECRET', 'whsec_...');  // optional: texts people send back

Why not a settings page? Because anything you save in the admin lives in the database, and the database gets copied around more than you think: a staging site, a backup plugin's archive, a SQL dump you send a developer. wp-config.php stays on the server. It also means there's no form to build, which keeps the plugin short enough to read in one go.

The one function that sends

Everything goes through sparetext_send(). It uses wp_remote_post, WordPress's own HTTP function, so it works on any host without asking for the cURL extension:

sparetext-sms.php
function sparetext_send(string $to, string $text, string $key = '')
{
    if (!defined('SPARETEXT_API_KEY') || SPARETEXT_API_KEY === '') {
        return new WP_Error('sparetext_no_key', 'Add SPARETEXT_API_KEY to wp-config.php.');
    }
    $server = defined('SPARETEXT_SERVER') ? SPARETEXT_SERVER : 'https://sparetext.dev';
    $headers = ['x-api-key' => SPARETEXT_API_KEY, 'content-type' => 'application/json'];
    if ($key !== '') {
        // Prefixed with this site, so two sites on one Sparetext account never share a key.
        $headers['idempotency-key'] = 'wp-' . substr(md5(home_url()), 0, 8) . '-' . $key;
    }
    $res = wp_remote_post("$server/api/v1/messages", [
        'headers' => $headers,
        'body'    => wp_json_encode(['to' => $to, 'text' => $text]),
        'timeout' => 15,
    ]);
    if (is_wp_error($res)) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- a failed text is logged on purpose
        error_log('Sparetext: ' . $res->get_error_message());
        return $res;
    }
    $status = wp_remote_retrieve_response_code($res);
    $body = json_decode(wp_remote_retrieve_body($res), true);
    if ($status >= 400) {
        $error = new WP_Error('sparetext_' . ($body['error']['code'] ?? 'error'), $body['error']['message'] ?? "HTTP $status");
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- a failed text is logged on purpose
        error_log("Sparetext: $status " . $error->get_error_message());
        return $error;
    }
    return $body;
}

Two things in there matter. A 401 or a 400 from the API isn't a network failure, so wp_remote_post won't return a WP_Error for it; the function checks the status itself and logs the API's own message. And the optional $key becomes an Idempotency-Key: send the same key twice within 24 hours and Sparetext queues the text once. That's what stops double texts below.

You can call it from anywhere too, a theme, a booking plugin, a cron job: sparetext_send('+12025550123', 'Your booking is confirmed.').

Text yourself about every new order

The tempting hook is woocommerce_thankyou, but it only fires when the customer actually sees the thank-you page. Pay on PayPal, close the tab instead of coming back, and no text. We hook the status change instead, which fires however the order gets there:

sparetext-sms.php
add_action('woocommerce_order_status_changed', function ($order_id, $from, $to, $order) {
    // A new order, paid (processing) or waiting for a bank transfer or cash on delivery (on-hold):
    // one text to you, even when it moves from on-hold to processing later.
    if (in_array($to, ['processing', 'on-hold'], true) && defined('SPARETEXT_NOTIFY') && !$order->get_meta('_sparetext_new_order')) {
        $order->update_meta_data('_sparetext_new_order', time());
        $order->save();
        // "USD 24.50", not wc_price(): its HTML hides a no-break space, which isn't in GSM-7, so the
        // whole text would go as UCS-2 and fit 70 characters a part instead of 160.
        $text = sprintf(
            'New order #%s: %s %s from %s %s.',
            $order->get_order_number(),
            $order->get_currency(),
            wc_format_decimal($order->get_total(), wc_get_price_decimals()),
            $order->get_billing_first_name(),
            $order->get_billing_last_name()
        );
        sparetext_send_later(SPARETEXT_NOTIFY, apply_filters('sparetext_new_order_text', $text, $order), "order-$order_id-new");
    }

An order paid by bank transfer goes to on-hold first, then to processing when the money lands. Without the _sparetext_new_order flag you'd get two texts for one order. In our test the order went on-hold, then processing, then completed, and the shop got exactly one text: New order #11: USD 24.50 from Ana Lopez.

That comment about the price is a real one, by the way. wc_price() gives you HTML with a no-break space between the symbol and the number. Strip the tags and it's still there, and it isn't in GSM-7, the alphabet a normal text uses. One character like that switches the whole text to UCS-2, where a part holds 70 characters instead of 160, so a two-line order alert can turn into two or three texts. The emoji post has the whole story. A plain USD 24.50 avoids it.

Don't make checkout wait

The order text doesn't go out right there in the hook. It goes through this:

sparetext-sms.php
function sparetext_send_later(string $to, string $text, string $key = ''): void
{
    if (function_exists('as_enqueue_async_action')) {
        as_enqueue_async_action('sparetext_send', [$to, $text, $key], 'sparetext');
    } else {
        sparetext_send($to, $text, $key);
    }
}
add_action('sparetext_send', 'sparetext_send', 10, 3);

WooCommerce ships with Action Scheduler, a background job queue. Status changes often happen inside the checkout request, so sending there means the customer's "Place order" spinner waits on a network call. Queued, it runs a moment later, and if the job ever runs twice, the order-11-new key means Sparetext still sends one text. In the test, the queue ran both order texts and the simulated phone reported them delivered.

Text the customer when the order is done

sparetext-sms.php
    // Done: one text to the customer, if they gave a phone number at checkout.
    if ($to === 'completed' && $order->get_billing_phone() && !$order->get_meta('_sparetext_completed')) {
        $order->update_meta_data('_sparetext_completed', time());
        $order->save();
        $text = sprintf(
            'Hi %s, your order #%s from %s is complete. Thank you!',
            $order->get_billing_first_name(),
            $order->get_order_number(),
            wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES)
        );
        sparetext_send_later($order->get_billing_phone(), apply_filters('sparetext_order_completed_text', $text, $order), "order-$order_id-completed");
    }
}, 10, 4);

Here's the thing about phone numbers in WooCommerce: they're stored exactly as the customer typed them. (202) 555-0157, 202-555-0161, sometimes with a country code, mostly without. You don't have to clean them up. Sparetext reads a number without a + in your account's country (Settings, Phone numbers), so in our test both of those arrived as +12025550157 and +12025550161 for a US account. A number that can't be in that country, like a UK mobile typed without +44, fails with an error that says exactly that, in your PHP error log.

Want different words? Every text has a filter, so you can change it from your theme's functions.php without touching the plugin:

functions.php
add_filter('sparetext_order_completed_text', function ($text, $order) {
    return "Hi {$order->get_billing_first_name()}, order #{$order->get_order_number()} is on its way!";
}, 10, 2);

The plugin reads and writes orders only through the order object, never the database directly, and it tells WooCommerce it's fine with HPOS, the newer order tables, so you won't see an "incompatible plugin" warning. We ran it on both: the classic order storage first, then HPOS, and each order texted once either way.

Contact Form 7 messages

sparetext-sms.php
// Before the email goes out, not after: if the site's email fails, which WordPress email often does,
// you still hear about the message.
add_action('wpcf7_before_send_mail', function ($form, &$abort, $submission) {
    if (!defined('SPARETEXT_NOTIFY') || !$submission) {
        return;
    }
    $data = $submission->get_posted_data();
    $name = sanitize_text_field($data['your-name'] ?? '');
    $email = sanitize_email((string) ($data['your-email'] ?? ''));
    $who = trim($name . ($email !== '' ? " <$email>" : ''));
    // Plain text for a phone, not HTML: sanitized, cut at 200 characters, and "I <3 it" kept, not "I &lt;3 it".
    $what = wp_specialchars_decode(wp_html_excerpt(sanitize_textarea_field($data['your-message'] ?? ''), 200, '...'), ENT_QUOTES);
    $text = sprintf('New message on %s from %s: %s', $form->title(), $who ?: 'someone', $what);
    sparetext_send(SPARETEXT_NOTIFY, apply_filters('sparetext_form_text', $text, $form, $data));
}, 10, 3);

The obvious hook is wpcf7_mail_sent, but it only fires when the email worked, which is exactly the case where you didn't need the text. wpcf7_before_send_mail fires after the spam checks and before the email, so a broken mail setup can't hide a message from you. We sent the default form through Contact Form 7's own REST endpoint and the phone got New message on Contact form 1 from Sam Rivera <sam@example.test>: Hi, can you do a birthday cake for 12 people on Saturday?

The fields are sanitized first, and the message is cut at 200 characters, so a long one doesn't turn into five texts. It stays plain text the whole way: "I <3 your lemon one" arrives as written, where stripping tags the usual way would have cut it off at the "<". On WPForms or Gravity Forms the idea is the same, with their hooks: wpforms_process_complete and gform_after_submission. We haven't run those two, so check their field names before you rely on it.

Get the replies back in WordPress

This is where sending from your own number pays off. When a customer answers "Yes, Saturday works", it lands on your phone like any text, and Sparetext also posts it to your site. The plugin adds a REST route for it:

sparetext-sms.php
add_action('rest_api_init', function () {
    register_rest_route('sparetext/v1', '/incoming', [
        'methods'             => 'POST',
        'permission_callback' => '__return_true', // the signature check below is the lock
        'callback'            => 'sparetext_incoming',
    ]);
});

function sparetext_incoming(WP_REST_Request $request)
{
    $raw = $request->get_body(); // the bytes as they arrived: the signature covers exactly these
    $secret = defined('SPARETEXT_WEBHOOK_SECRET') ? SPARETEXT_WEBHOOK_SECRET : '';
    if ($secret === '' || !sparetext_signed($raw, (string) $request->get_header('x-sparetext-signature'), $secret)) {
        return new WP_REST_Response(['error' => 'bad signature'], 401);
    }
    $event = json_decode($raw, true);
    // A webhook that didn't get a 2xx in time is sent again with the same id: handle each id once.
    $seen = 'sparetext_evt_' . md5((string) ($event['id'] ?? ''));
    if (get_transient($seen)) {
        return new WP_REST_Response(null, 200);
    }
    set_transient($seen, 1, 4 * DAY_IN_SECONDS);

    if (($event['type'] ?? '') === 'message.received' && is_array($event['data']['message'] ?? null)) {
        $message = $event['data']['message'];
        do_action('sparetext_message_received', $message);
        // A plain-text email: anything that looks like HTML is dropped, the words are kept as they were sent.
        $from = sanitize_text_field($message['contact'] ?? '');
        $words = wp_specialchars_decode(sanitize_textarea_field($message['text'] ?? ''), ENT_QUOTES);
        wp_mail(get_option('admin_email'), "Text from $from", $words);
    }
    return new WP_REST_Response(null, 200);
}

On Sparetext's Webhooks page, add https://your-site.com/wp-json/sparetext/v1/incoming with Text received ticked, and copy its secret into SPARETEXT_WEBHOOK_SECRET. permission_callback is open on purpose, since Sparetext doesn't log in to your WordPress. The signature is what keeps strangers out:

sparetext-sms.php
function sparetext_signed(string $raw, string $header, string $secret): bool
{
    if (!preg_match('/(?:^|,)t=(\d+)/', $header, $t) || abs(time() - (int) $t[1]) > 300) {
        return false; // missing, or more than five minutes off: maybe a replayed request
    }
    $want = hash_hmac('sha256', "$t[1].$raw", $secret);
    preg_match_all('/v1=([0-9a-f]{64})/', $header, $v1);
    foreach ($v1[1] as $got) {
        if (hash_equals($want, $got)) {
            return true; // two v1 values for a day after the secret is rotated
        }
    }
    return false;
}

The once-per-id part isn't theory. Sparetext waits 5 seconds for an answer, then tries again. In our test WordPress was slow (it was running PHP in WebAssembly), the first try took longer than 5 seconds, and Sparetext sent the same event again 5 seconds later. WordPress had already handled the first one, so the second got a quick 200 and the reply was emailed once, not twice. A slow shared host or an SMTP plugin that takes its time can do the same to you. A POST without a signature got a 401.

sparetext_message_received is there for your own code: put the reply on the order as a note, mark a booking confirmed, whatever fits. The webhook guide lists every event, and how retries work over the 3 days Sparetext keeps trying.

What this can't do

A phone is the right tool for texts to people who know you: order updates, booking reminders, an alert to you or your team, a conversation with a customer. Only text customers about their own order, and keep anything like marketing to people who asked for it.

It's the wrong tool for blasting a mailing list. Carriers filter business texts sent by software even from a personal number, and the 10DLC post explains why. An Android phone sends about 30 texts a minute, which is plenty for a shop and nowhere near enough for a flash sale to 20,000 people. On plans, Free covers 300 texts a month and Pro 10,000 on up to 5 phones (pricing).

Not on WordPress? Send SMS from PHP does the same with plain cURL, and the PHP examples have a send that's safe to retry and a webhook receiver for Laravel or anything else.

Try it on your own shop

Pair your phone, make a key, drop the plugin into wp-content/plugins, add the three lines to wp-config.php, and place a test order. When your pocket buzzes with "New order", you'll never go digging in the spam folder for one again.

wordpresswoocommercephpsend smssms plugincontact form 7webhookstutorial

Try it with the phone you have

Free for 1 phone and 300 texts a month. Pair it in about two minutes.

Start free

Responses

Sign in or create an account to respond.

More from the blog