To update WordPress from a Google Sheet, put a small secret-gated REST endpoint on the site (a one-file MU-plugin that calls wp_update_post) and have an Apps Script in the sheet POST each row to it. Press a button, the posts update, each row turns green. This guide builds that push first, then covers reading a sheet from PHP, safe batch writes, triggers and two-way sync, a multi-site controller, and recipes for custom fields, SEO meta, directories, menus, events and featured images.
Editing posts one at a time in wp-admin is fine for three posts and miserable for three hundred. When the content already lives in a spreadsheet (a content team owns it, it came from a supplier feed, it's a list of locations), the fastest workflow is to keep editing it there and move the changes into WordPress in one step. No plugin marketplace, no CSV import dance, no logging into wp-admin at all.
The shape of it

Three pieces: the receiver (a WordPress REST route), the sender (an Apps Script bound to the sheet), and a shared secret so the route only listens to you. Build them in that order.
The WordPress side: a one-file MU-plugin
Drop this in wp-content/mu-plugins/te-sheet-sync.php. MU-plugins load automatically and can't be deactivated by accident, which is what you want for an integration endpoint.
<?php
/**
* Plugin Name: TE Sheet Sync
* Plugin URI: https://techearl.com/wordpress-update-from-google-sheet-rest-api
* Description: Receives post edits pushed from a Google Sheet over an authenticated REST request.
* Author: Ishan Karunaratne
* Author URI: https://techearl.com
*/
defined( 'ABSPATH' ) || exit;
const TE_SHEET_NS = 'te-sheet/v1';
add_action( 'rest_api_init', function () {
register_rest_route( TE_SHEET_NS, '/post', array(
'methods' => 'POST',
'callback' => 'te_sheet_update_post',
'permission_callback' => 'te_sheet_authorize',
'args' => array(
'post_id' => array( 'required' => true, 'sanitize_callback' => 'absint' ),
'title' => array( 'sanitize_callback' => 'sanitize_text_field' ),
'excerpt' => array( 'sanitize_callback' => 'sanitize_textarea_field' ),
),
) );
} );
/**
* Authorize before the handler runs. Constant-time compare of the key sent in
* the X-TE-Key header against the secret stored in wp-config.php.
*/
function te_sheet_authorize( WP_REST_Request $request ): bool {
if ( ! defined( 'TE_SHEET_SECRET' ) || '' === TE_SHEET_SECRET ) {
return false;
}
$sent = (string) $request->get_header( 'x-te-key' );
return '' !== $sent && hash_equals( TE_SHEET_SECRET, $sent );
}
/**
* Apply one row from the sheet to one post.
*/
function te_sheet_update_post( WP_REST_Request $request ) {
$id = (int) $request['post_id'];
if ( 'post' !== get_post_type( $id ) ) {
return new WP_Error( 'te_not_found', 'No editable post with that ID.', array( 'status' => 404 ) );
}
$patch = array( 'ID' => $id );
if ( null !== $request['title'] ) {
$patch['post_title'] = $request['title'];
}
if ( null !== $request['excerpt'] ) {
$patch['post_excerpt'] = $request['excerpt'];
}
$result = wp_update_post( $patch, true );
if ( is_wp_error( $result ) ) {
return new WP_Error( 'te_update_failed', $result->get_error_message(), array( 'status' => 500 ) );
}
return array(
'code' => 200,
'updated' => $id,
'title' => get_the_title( $id ),
);
}If you want the mechanics of register_rest_route on their own (namespace convention, methods, the args map, returning WP_REST_Response or WP_Error), I cover that in adding a custom REST API endpoint in WordPress. This article is that pattern put to a specific job. Three things in there matter more than the rest:
permission_callbackis the gate, and it runs before the handler. A common mistake is settingpermission_callbackto__return_trueand then checking the key inside the handler. Do the check inpermission_callbackso an unauthorized request never reaches your update logic.hash_equalscompares the secret in constant time. A plain===on a secret leaks timing information an attacker can use to guess it byte by byte.hash_equalsis the right tool any time you compare a secret.- Every field is sanitized at the door via
sanitize_callback, andpost_idis forced throughabsint. The handler refuses anything that isn't an existingpost, so a stray ID can't create or clobber the wrong object.
The secret lives in wp-config.php, never in the plugin file and never in the repo:
define( 'TE_SHEET_SECRET', 'a-long-random-string-from-a-password-manager' );One requirement that's easy to forget: the WordPress site has to be reachable over HTTPS from the public internet, because Apps Script runs on Google's servers, not on your machine. Any real production site already is.
Test the endpoint before touching the sheet
Prove the auth works with curl first. No key and a wrong key should both be rejected; the correct key should apply the change.
URL="https://example.com/wp-json/te-sheet/v1/post"
# 1. No key -> 401
curl -s -o /dev/null -w '%{http_code}\n' -X POST "$URL" -d 'post_id=42&title=nope'
# 2. Wrong key -> 401
curl -s -o /dev/null -w '%{http_code}\n' -X POST "$URL" -H 'X-TE-Key: wrong' -d 'post_id=42&title=nope'
# 3. Correct key -> 200, and the post is updated
curl -s -X POST "$URL" -H "X-TE-Key: $TE_SHEET_SECRET" \
-d 'post_id=42&title=Brewing the Perfect Cup&excerpt=A practical guide.'The first two return 401. WordPress derives that status from rest_authorization_required_code(), which returns 401 when the request isn't logged in (an unauthenticated curl like this) and 403 when it is, so a bare curl with no WordPress cookie gets the 401 you see here. The third returns {"code":200,"updated":42,"title":"Brewing the Perfect Cup"} and the change is live. If that works, the WordPress half is done.
The Google Sheet
Lay the sheet out so each row is one post and one column is the WordPress post ID. A status column gives the script somewhere to report back.

post_id is the join key between the sheet and WordPress. new_title and new_excerpt are what you want applied. current_title is just there for your own sanity while editing, the script ignores it.
The Apps Script: a "Push to WordPress" button
In the sheet, open Extensions → Apps Script and paste this. It adds a custom menu and, on click, POSTs each row to the endpoint.
/**
* TE Sheet Sync: push spreadsheet rows to WordPress over a REST request.
*/
const TE_ENDPOINT = PropertiesService.getScriptProperties().getProperty('TE_ENDPOINT');
const TE_KEY = PropertiesService.getScriptProperties().getProperty('TE_KEY');
/** Build the custom menu when the spreadsheet opens. */
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('TechEarl')
.addItem('Push to WordPress', 'tePushToWordPress')
.addToUi();
}
/** Read every row and POST it to WordPress, colouring the status cell per result. */
function tePushToWordPress() {
const sheet = SpreadsheetApp.getActiveSheet();
const values = sheet.getDataRange().getValues();
const head = values[0];
const col = name => head.indexOf(name);
for (let r = 1; r < values.length; r++) {
const postId = values[r][col('post_id')];
if (!postId) continue;
const ok = tePost('post', {
post_id: postId,
title: values[r][col('new_title')],
excerpt: values[r][col('new_excerpt')],
});
const cell = sheet.getRange(r + 1, col('status') + 1);
cell.setValue(ok ? 'updated' : 'failed');
cell.setBackground(ok ? '#d9ead3' : '#f4cccc');
}
SpreadsheetApp.flush();
}
/** POST one JSON payload to the endpoint. Returns true on HTTP 200. */
function tePost(path, payload) {
const res = UrlFetchApp.fetch(TE_ENDPOINT + '/' + path, {
method: 'post',
contentType: 'application/json',
headers: { 'X-TE-Key': TE_KEY },
payload: JSON.stringify(payload),
muteHttpExceptions: true,
});
return res.getResponseCode() === 200;
}
Notice the script reads TE_ENDPOINT and TE_KEY from Script Properties, not from hardcoded constants. That keeps the secret out of the code you'd screenshot, share, or paste into a support thread. Set them once under Project Settings → Script Properties (TE_ENDPOINT = https://example.com/wp-json/te-sheet/v1, TE_KEY = the same value as TE_SHEET_SECRET).
The first run prompts for authorization (the script needs permission to read the sheet and to make external requests). Approve it once. After that, reload the sheet and the custom menu appears:

Run it
Here are the eight posts before the push, all with rough placeholder titles:

Click TechEarl → Push to WordPress. The script walks the rows, POSTs each one, and paints each status cell green on success (or red on failure, so a partial run is obvious at a glance):

And the posts in WordPress now carry the titles from the sheet:

Eight posts in one click. The same loop scales to hundreds, with the practical limit being Apps Script's per-execution runtime (six minutes per run, which now applies to both consumer Gmail and Google Workspace accounts) rather than anything on the WordPress side. For very large sheets, batch the rows or push only the ones whose status isn't already updated. Past a few thousand rows the cleaner option is to flip the direction entirely: have WordPress pull the sheet server-side with a service account on a WP-CLI cron, which has no six-minute ceiling.
Securing a public write endpoint
This endpoint accepts writes from the open internet, so the auth is not optional. The shared-secret-in-a-header approach above is the sane baseline. Here's the checklist, from baseline to hardened:
- Secret in a header, not the body or the URL. Headers stay out of server access logs and browser history. The body works too, but a header is cleaner.
- Constant-time compare (
hash_equals), never===. - Check in
permission_callback, so unauthorized requests never reach the handler. - HTTPS only, so the secret isn't sent in cleartext. Reject plain HTTP.
- Keep the secret out of code and version control.
wp-config.phpconstant on the WordPress side, Script Properties on the Apps Script side. - Rotate the secret if it ever leaks, and treat it like a password (long, random, from a manager).
If you need to go further, the next steps are an HMAC signature (sign the payload so the secret itself never travels), a timestamp plus nonce to stop replayed requests, and rate limiting on repeated bad keys. The full layer-by-layer hardening, with each step measured against real requests, is in securing a WordPress REST API write endpoint. For most internal "the marketing team edits a sheet" workflows, the header secret over HTTPS is enough; reach for HMAC when the endpoint is doing something you'd hate to see replayed.
WordPress also ships Application Passwords for REST auth, which is the right call if you're hitting core endpoints. For a small custom route like this, a dedicated shared secret keeps the surface area tiny and the code obvious.
Read a Google Sheet in PHP: CSV vs the API
The push above needs no Google credentials because the sheet does the talking. Every server-side job further down (the pull, two-way sync, the vertical recipes) reverses that: WordPress reads the sheet itself. There are two ways to do that from PHP, and the exposure difference is the whole decision.
Publish to web as CSV. In the sheet, File → Share → Publish to web → CSV. Google hands you a URL that returns the tab as CSV:
$url = 'https://docs.google.com/spreadsheets/d/e/<published-id>/pub?gid=0&single=true&output=csv';
$rows = array_map( 'str_getcsv', file( $url, FILE_IGNORE_NEW_LINES ) );
$head = array_shift( $rows );
foreach ( $rows as $row ) {
$data = array_combine( $head, $row );
// $data['post_id'], $data['new_currency'], ...
}No credentials, no tokens, no libraries. The cost is in the second word of "publish to web": the sheet is now public. Anyone with that URL reads the data, and a published URL turns up in code, logs, referrer headers and browser history; once it is out you cannot fully recall it. It is the right tool for data that is genuinely public anyway (a price list you'd put on the site regardless) and the wrong tool for anything you would not paste into a public Gist. CSV is also positional: inserting or reordering columns shifts what str_getcsv hands back, so combine rows with the header (array_combine) at minimum.
Read through the Sheets API with a service account. The sheet stays private. Create a service account in the Google Cloud console, enable the Google Sheets API, download its JSON key, and share the sheet with the service account's email (Viewer is enough to read). The key never goes in the repo; keep it outside the web root, reference it by path, and treat it like a password.
The difference is visible. The same private sheet, hit without a token, is refused; hit with the service account's token, it returns the rows:

| Publish-to-web CSV | Sheets API + service account | |
|---|---|---|
| Setup | one menu click | service account, key, share |
| Credentials | none | a JSON key on the server |
| Who can read the data | anyone with the URL | only the authenticated account |
| Revoke access | unpublish (and hope no copies) | delete the key or unshare |
| Right for | genuinely public data | anything private |
There is no SDK requirement for the API path. A service-account token is a signed JWT exchanged for an access token, and PHP can mint it with openssl_sign and WordPress's HTTP API. These two helpers are shared by every server-side command on this page; each plugin includes them behind a function_exists guard so two commands can live on one site without a redeclare collision:
if ( ! function_exists( 'te_sheet_token' ) ) {
/** Base64url-encode (JWT segments are unpadded and use -_ instead of +/). */
function te_b64url( $s ) { return rtrim( strtr( base64_encode( $s ), '+/', '-_' ), '=' ); }
/**
* Mint a short-lived access token from the service-account key (JWT bearer grant).
* The scope defaults to read-only; pass the read-write Sheets scope when you need
* to write back into the sheet.
*/
function te_sheet_token( array $key, string $scope = 'https://www.googleapis.com/auth/spreadsheets.readonly' ) {
$now = time();
$header = te_b64url( wp_json_encode( array( 'alg' => 'RS256', 'typ' => 'JWT' ) ) );
$claims = te_b64url( wp_json_encode( array(
'iss' => $key['client_email'],
'scope' => $scope,
'aud' => 'https://oauth2.googleapis.com/token',
'iat' => $now,
'exp' => $now + 3600,
) ) );
$sig = '';
openssl_sign( "{$header}.{$claims}", $sig, $key['private_key'], 'sha256WithRSAEncryption' );
$jwt = "{$header}.{$claims}." . te_b64url( $sig );
$res = wp_remote_post( 'https://oauth2.googleapis.com/token', array(
'body' => array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt,
),
) );
return json_decode( wp_remote_retrieve_body( $res ), true )['access_token'] ?? '';
}
/**
* Read a sheet range over the Sheets API. Returns the raw rows, header row included.
* Throws on any failed read, so a caller never mistakes "could not read" for "sheet is empty".
*/
function te_sheet_read( string $sheet_id, string $range, string $token ): array {
$url = sprintf( 'https://sheets.googleapis.com/v4/spreadsheets/%s/values/%s', rawurlencode( $sheet_id ), rawurlencode( $range ) );
$res = wp_remote_get( $url, array( 'headers' => array( 'Authorization' => "Bearer {$token}" ) ) );
if ( is_wp_error( $res ) ) {
throw new RuntimeException( 'Sheets API request failed: ' . $res->get_error_message() );
}
$code = wp_remote_retrieve_response_code( $res );
$body = json_decode( wp_remote_retrieve_body( $res ), true );
if ( 200 !== $code || ! is_array( $body ) ) {
throw new RuntimeException( "Sheets API returned HTTP {$code}." );
}
return $body['values'] ?? array(); // a genuinely empty range has no 'values' key
}
}Reach for CSV only when the data is public anyway. For anything behind a login, anything with personal data, or anything a competitor would enjoy reading, the service account is the baseline: a private, auditable, revocable connection instead of a public URL you can never fully un-share.
With reading solved, the two directions compare like this:
| Push (REST endpoint) | Pull (service account) | |
|---|---|---|
| Initiated by | the sheet (button / onEdit) | WordPress (cron / CLI) |
| Google credentials | none | a service account |
| Best for | a human deciding "push now" | scheduled, hands-off reconciliation |
| Auth lives in | a shared secret in WordPress | a service-account key on the server |
Safely bulk-update custom fields
Any bulk write to post meta should preview changes before writing, verify a private backup before the first mutation, and record every attempted change. The downloadable Safe Batch plugin implements that workflow for one native text-meta key on at most 5,000 posts, with a separate restore command. It is a bounded example for PHP 8.1+ and WP-CLI: it rejects duplicate values, arrays, objects and oversized values rather than claim it can restore arbitrary WordPress or ACF data. Pause editors, cron jobs and other importers during a live run; its file lock coordinates its own runs, not every writer on the site.
Download te-safe-batch.php, inspect it, place it in wp-content/plugins/te-safe-batch.php, then activate it:
wp plugin activate te-safe-batch
wp help te-batch update_meta
wp help te-batch restoreIt registers wp te-batch update_meta and wp te-batch restore (the underscore in update_meta is part of the command name). Run the preview first; it prints one JSON record per proposed change, with the post ID and previous/new value lists:
wp te-batch update_meta --meta_key=currency --value=USD --post_type=postAn empty list means the key was absent; a list containing an empty string means the key existed with an empty value. That distinction matters when restoring. Preview output can contain the field's values, so do not capture sensitive fields in a shared terminal log. The query covers the selected post type and WordPress's any post-status set (which does not mean literally every status) and refuses more than 5,000 posts. It holds its plan in memory and does not promise constant memory; partition larger jobs and use the WP-CLI bulk-script guide to design checkpoints.
| Check | What the plugin actually does |
|---|---|
| Dry run | Reads the proposed changes and prints them; creates no backup, journal or meta writes |
| Backup gate | Creates an exclusive private snapshot, checks full writes and synchronization, then reads it back byte-for-byte |
| Journal gate | Opens a private journal and synchronizes its start record before the first database write |
| Checked writes | Rechecks the old value, records the attempt, writes, verifies the stored value and records the result |
The critical write sequence, abbreviated from the download:
// Abbreviated from the downloadable plugin; not a second standalone plugin.
$this->record( $journal, array( 'event' => 'attempt', 'entry' => $entry ) );
$result = $entry['after']
? update_post_meta( $id, wp_slash( $key ), wp_slash( $entry['after'][0] ) )
: delete_post_meta( $id, wp_slash( $key ) );
if ( false === $result || $this->values( $id, $key ) !== $entry['after'] ) {
$this->record( $journal, array( 'event' => 'failed', 'id' => $id ) );
throw new RuntimeException( "Post {$id} failed verification; earlier posts may have changed." );
}
$this->record( $journal, array( 'event' => 'applied', 'id' => $id ) );update_post_meta() returning false can mean an unchanged value or a failure; the plan already excludes no-ops, and each write is followed by a value check. wp_slash() preserves literal backslashes and quotes across WordPress's metadata write handling. The plugin also rejects stored keys that compare equal under the database collation but differ in spelling (Currency and currency), so it never changes a field missing from the snapshot.
For a live run, create the backup directory as the WP-CLI user, outside ABSPATH and every other served directory or web-server alias:
install -d -m 700 "$HOME/te-batch-backups"
wp te-batch update_meta --meta_key=currency --value=USD
wp te-batch update_meta --meta_key=currency --value=USD \
--backup-dir="$HOME/te-batch-backups" --liveThe plugin rejects a missing or unwritable directory, one inside WordPress, content or uploads, or one with group/world permissions. It cannot discover every web-server alias, so check the location yourself. A live run prints its actual snapshot and journal paths; a second identical run reports no changes. To undo, use the printed path:
wp te-batch restore --backup=/srv/private/te-batch-SNAPSHOT_ID.json
wp te-batch restore --backup=/srv/private/te-batch-SNAPSHOT_ID.json --liveThe first call previews, the second applies. Restoration rejects the wrong site context, missing posts and duplicate entries, and refuses to overwrite a field that no longer matches either the original or the intended value, so unrelated later edits need a manual decision. An originally absent key is deleted; an originally empty string comes back as an empty value. This is not an all-or-nothing transaction: a failure leaves a partial run, and an attempt with no result record has an uncertain outcome, so inspect the actual value rather than assume. Test it on a disposable database first (dry run leaves everything unchanged, a bad backup directory fails before any write, a simulated database failure stops the run and preserves the snapshot, repeated runs change nothing).
ACF fields need a field-specific updater. Do not blindly swap get_post_meta() for get_field() in this plugin. ACF formatted values, field-reference rows, Repeaters, relationships and images have different storage and restoration needs; ACF versus native metadata explains the distinction. For WooCommerce, use product CRUD so lookup tables and caches stay consistent; the WooCommerce sheet updater has its own data model.
Three ways to trigger it
The button is the simplest trigger, but it isn't the only one:
- Button (shown above). A
onOpencustom menu. Best when a human decides "push now." - On edit. An installable
onEdittrigger that fires when a specific column changes, so editing a cell pushes that one row immediately. Filter hard on the sheet and column inside the handler, becauseonEditfires on every edit. - Scheduled. A time-driven trigger that pushes the whole sheet on a schedule (hourly, nightly), or a system cron running a server-side pull. Good for feeds that change on their own.
All three call the same push logic. Start with the button and add the others only when you actually need them. If you want WordPress to write its current state back into the sheet so the sheet never goes stale, that is a two-way sync; running the same push across a fleet of separate installs is the multi-site controller.
Push a sheet edit with an onEdit trigger
To push a change the instant a cell changes, use an installable onEdit trigger that POSTs the edited row to the same endpoint. Apps Script has two onEdit triggers and they are not interchangeable:
- A simple trigger (a function literally named
onEdit) runs automatically but in a restricted security context. It cannot callUrlFetchApp, so it cannot reach your site at all. Wire your push into a function namedonEditand it will silently do nothing. - An installable trigger (any function name, registered under Triggers) runs with your full authorization and can make external requests. Installing it is what prompts the one-time authorization.
Name the handler something other than onEdit so it is unmistakably the installable one, and add it to the same script (it reuses TE_ENDPOINT and TE_KEY):
/** Installable onEdit handler: push the edited row to WordPress. */
function teOnEdit(e) {
const sheet = e.range.getSheet();
// Filter hard. onEdit fires on every edit in the spreadsheet.
if (sheet.getName() !== 'Sheet1') return; // right tab only
const row = e.range.getRow();
const col = e.range.getColumn();
if (row === 1) return; // skip the header
const head = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
const WATCH = ['new_title', 'new_excerpt']; // only these columns push
if (!WATCH.includes(head[col - 1])) return; // match by header, not position
const vals = sheet.getRange(row, 1, 1, sheet.getLastColumn()).getValues()[0];
const get = name => vals[head.indexOf(name)];
const ok = tePost('post', {
post_id: get('post_id'),
title: get('new_title'),
excerpt: get('new_excerpt'),
});
// Feedback: paint the status cell so a failed push is impossible to miss.
const statusCol = head.indexOf('status') + 1;
if (statusCol > 0) {
const cell = sheet.getRange(row, statusCol);
cell.setValue(ok ? 'updated' : 'failed');
cell.setBackground(ok ? '#d9ead3' : '#f4cccc');
}
}Then Triggers → Add Trigger: choose teOnEdit, event source From spreadsheet, event type On edit, and approve the authorization prompt.

When it fires, it makes exactly the authenticated request from the curl test, and the post updates:

onEdit is noisy by design, so keep it from hammering the site: filter on sheet name and column before any work (the early returns stop most irrelevant fires), ignore the header row, and for a column someone edits rapidly, debounce by storing the last push time per row in PropertiesService. Point it at a staging endpoint while you tune the column filter, because an edit-driven trigger can send a half-typed value mid-edit. For many rows at once, use the button or the server-side pull; onEdit is for the one-row, edit-and-see-it-live workflow.
Two-way sync between WordPress and a Google Sheet
A two-way sync runs two jobs on a schedule: WordPress writes its state back into the sheet, and sheet edits flow into WordPress. The plumbing is easy. The hard part is deciding which side wins when the same row was edited in both places, and a two-way sync that hasn't answered that is a data-loss bug with a cron schedule.

Writing WordPress back into the sheet
Reading uses spreadsheets.values.get; writing back is spreadsheets.values.batchUpdate, which sets one or more ranges in a single request. Two things change from a read-only pull: share the sheet with the service account as Editor, not Viewer, and request the read-write scope https://www.googleapis.com/auth/spreadsheets. The body is a list of data entries (a range plus a 2D values array) and a valueInputOption. RAW stores exactly what you send; USER_ENTERED parses each value as if typed, so "42" becomes a number, a date string becomes a date, and a leading = becomes a formula. For syncing data you almost always want RAW.
/**
* Write rows back into the sheet in one batch. $updates is a list of
* [ 'range' => 'Sheet1!C2', 'value' => 'published' ] entries.
*/
function te_sheet_write( $sheet_id, array $updates, array $key ): bool {
$token = te_sheet_token( $key, 'https://www.googleapis.com/auth/spreadsheets' );
if ( ! $token ) {
return false;
}
$data = array();
foreach ( $updates as $u ) {
$data[] = array(
'range' => $u['range'],
'values' => array( array( $u['value'] ) ),
);
}
$url = sprintf(
'https://sheets.googleapis.com/v4/spreadsheets/%s/values:batchUpdate',
rawurlencode( $sheet_id )
);
$res = wp_remote_post( $url, array(
'headers' => array(
'Authorization' => "Bearer {$token}",
'Content-Type' => 'application/json',
),
'body' => wp_json_encode( array(
'valueInputOption' => 'RAW',
'data' => $data,
) ),
) );
return 200 === (int) wp_remote_retrieve_response_code( $res );
}One request updates every changed cell. That batching matters: the Sheets API meters reads and writes per minute (300 per project, 60 per user, returning 429 over the limit), so a thousand single-cell writes is a rate-limit incident, while one values:batchUpdate is a single call. Google has signalled that over-quota usage is planned to start incurring Cloud billing charges later in 2026, which is one more reason to batch.
Who wins: one owner per field
Picture one cycle: at 09:00 someone fixes a price in WordPress; at 09:15 someone fixes the title of the same product in the sheet; the sync runs at 09:20. Copy the sheet onto WordPress and you resurrect the old price; copy WordPress onto the sheet and you overwrite the new title. Both edits were correct, one is destroyed, nobody gets an error. That is last-write-wins, and it is the absence of a strategy.
| Strategy | How it decides | Good for |
|---|---|---|
| Per-field ownership | Each column has one authoritative side; it only ever syncs one way | Most real cases. Simple, and impossible to get a conflict |
| Timestamp arbitration | Whichever side was edited more recently wins that row | Fields both sides genuinely edit |
| Dirty-flag tracking | A "changed since last sync" marker per side decides direction | When edits are rare and you want zero accidental overwrites |
For almost every WordPress-and-a-sheet setup, per-field ownership is the answer: price and stock are owned by WordPress, an editorial "notes" column is owned by the sheet, and the two arrows never touch the same cell. For a field both sides truly edit, use timestamps (WordPress has post_modified; add an edited_at column to the sheet).
The command reads both sides and routes each difference by an ownership map (it includes the shared helpers above and te_sheet_write(); the whole thing lives in wp-content/plugins/te-sheet-two-way-sync/te-sheet-two-way-sync.php):
class TE_Sheet_Sync_Command {
/** Which side owns each column. Owned-by-WP flows out to the sheet; owned-by-sheet flows in. */
private const OWNER = array(
'price' => 'wp', // WordPress is the source of truth for price
'stock' => 'wp', // and for stock
'notes' => 'sheet', // the team owns the editorial notes column
);
/**
* Reconcile the sheet and WordPress. Dry run unless --live.
*
* ## OPTIONS
* --sheet=<id> : Spreadsheet ID.
* --key=<path> : Path to the service-account JSON key.
* [--range=<a1>]: Sheet range, starting at column A with the header in row 1. Default: Sheet1!A:D
* [--live] : Actually write. Without it, dry run.
*/
public function sync( $args, $assoc ): void {
$key = json_decode( file_get_contents( $assoc['key'] ), true );
$range = $assoc['range'] ?? 'Sheet1!A:D';
$live = isset( $assoc['live'] );
// Write-back targets are built as <tab>!<col><row>, so the range must start at A1.
if ( ! preg_match( '/^(.+)!A1?:[A-Z]+\d*$/', $range, $m ) ) {
WP_CLI::error( 'Use a range that starts at column A, row 1, e.g. Sheet1!A:D.' );
}
$tab = $m[1];
$token = te_sheet_token( $key, 'https://www.googleapis.com/auth/spreadsheets' );
if ( ! $token ) { WP_CLI::error( 'Could not get an access token.' ); }
$rows = te_sheet_read( $assoc['sheet'], $range, $token );
$head = array_shift( $rows ); // e.g. [ post_id, price, stock, notes ]
$cols = array_flip( $head );
$to_wp = array(); // sheet -> WordPress (owned-by-sheet fields)
$to_sheet = array(); // WordPress -> sheet (owned-by-wp fields)
foreach ( $rows as $i => $row ) {
$post_id = (int) ( $row[ $cols['post_id'] ] ?? 0 );
if ( ! $post_id ) { continue; }
$rownum = $i + 2; // 1-based, plus the header row
foreach ( self::OWNER as $field => $owner ) {
if ( ! isset( $cols[ $field ] ) ) { continue; }
$sheet_val = (string) ( $row[ $cols[ $field ] ] ?? '' );
$wp_val = (string) get_post_meta( $post_id, $field, true );
if ( $sheet_val === $wp_val ) { continue; } // already in step
if ( 'sheet' === $owner ) {
$to_wp[] = array( 'id' => $post_id, 'field' => $field, 'new' => $sheet_val, 'dir' => 'to WP' );
} else {
$colA1 = chr( 65 + $cols[ $field ] ); // A, B, C ...
$to_sheet[] = array( 'id' => $post_id, 'field' => $field, 'new' => $wp_val,
'dir' => 'to sheet', 'range' => "{$tab}!{$colA1}{$rownum}", 'value' => $wp_val );
}
}
}
$plan = array_merge( $to_wp, $to_sheet );
if ( empty( $plan ) ) { WP_CLI::success( 'Sheet and WordPress already in step.' ); return; }
WP_CLI\Utils\format_items( 'table', $plan, array( 'id', 'field', 'dir', 'new' ) );
if ( $live ) {
foreach ( $to_wp as $u ) { update_post_meta( $u['id'], $u['field'], $u['new'] ); }
if ( $to_sheet && ! te_sheet_write( $assoc['sheet'], $to_sheet, $key ) ) {
// WordPress already took its side; the sheet did not. The next run retries,
// because those cells still differ, but say so instead of reporting success.
WP_CLI::error( sprintf(
'Partial sync: %d written to WordPress, %d sheet write(s) failed and will retry next run.',
count( $to_wp ), count( $to_sheet )
) );
}
}
$mode = $live ? 'reconciled' : 'WOULD reconcile (dry run)';
WP_CLI::success( sprintf(
'%d %s: %d to WordPress, %d to the sheet.',
count( $plan ), $mode, count( $to_wp ), count( $to_sheet )
) );
}
}
WP_CLI::add_command( 'te-sheet', 'TE_Sheet_Sync_Command' );The dry run's dir column shows which way each change is about to move before anything is written. If a field shows up going the wrong direction, the OWNER map is wrong, not the data:

Scheduling the sync
Do not lean on WP-Cron for this: it only fires when someone loads a page, so a low-traffic site can skip a scheduled sync for hours. Disable it and drive WP-CLI from system cron:
// wp-config.php
define( 'DISABLE_WP_CRON', true );# crontab: reconcile every 15 minutes, server-side, no browser involved
*/15 * * * * cd /var/www/site && wp te-sheet sync --sheet=SHEET_ID --key=/etc/te/sa-key.json --live >/dev/null 2>&1The sheet side has its own scheduler, an installable time-driven trigger, if you would rather the sheet drive the cadence:
// Run once to install; fires roughly every hour thereafter.
ScriptApp.newTrigger('teReconcile').timeBased().everyHours(1).create();Time-driven triggers fire within a window, not on the dot, so do not build anything that assumes it ran at exactly :00. Apps Script runs on V8 (Google began migrating compatible scripts on February 18, 2020), so let/const, arrow functions and classes work in the bound script.
Manage multiple WordPress sites from one sheet
To run a fleet of separate WordPress installs from one sheet, add a website column and put a controller in front of it. Every site runs the same one-file MU-plugin from the top of this page with its own secret; the controller groups the rows by site and pushes each site its own batch, so a dead site fails on its own line and the rest still land.

| website | post_id | title |
|---|---|---|
| blog-a | 1 | Spring Campaign: 20% Off Storewide |
| blog-a | 5 | Spring Campaign: Start Your Free Trial |
| shop-b | 6 | Spring Campaign: Summer Sale Is Live |
| shop-b | 7 | Spring Campaign: Free Shipping Weekend |
| events-c | 3 | Spring Campaign: Early-Bird Tickets |
The registry maps each website to its endpoint and key. Per-site secrets contain a leak to one install and let you rotate one key without touching the others; the keys come from the environment, never the source:
$te_sites = array(
'blog-a' => array( 'url' => 'https://blog-a.example/wp-json/te-sheet/v1', 'key' => getenv( 'TE_KEY_BLOG_A' ) ),
'shop-b' => array( 'url' => 'https://shop-b.example/wp-json/te-sheet/v1', 'key' => getenv( 'TE_KEY_SHOP_B' ) ),
'events-c' => array( 'url' => 'https://events-c.example/wp-json/te-sheet/v1', 'key' => getenv( 'TE_KEY_EVENTS_C' ) ),
);The controller (fleet-push.php on a control machine, not a plugin on any managed site) reads the sheet with the shared helpers, groups by website, and pushes each batch:
/** Group the sheet rows by their target site. */
function te_group_by_site( array $rows ): array {
$by_site = array();
foreach ( $rows as $row ) {
$site = $row['website'] ?? '';
if ( '' !== $site ) { $by_site[ $site ][] = $row; }
}
return $by_site;
}
/** Push one site's batch. Returns [ ok, failed, unreachable ]. */
function te_push_site( array $cfg, array $rows ): array {
$ok = 0; $failed = 0;
foreach ( $rows as $row ) {
$ch = curl_init( $cfg['url'] . '/post' );
curl_setopt_array( $ch, array(
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3, // give up reaching a dead site fast
CURLOPT_TIMEOUT => 8,
CURLOPT_HTTPHEADER => array( 'X-TE-Key: ' . $cfg['key'] ),
CURLOPT_POSTFIELDS => http_build_query( array(
'post_id' => $row['post_id'],
'title' => $row['title'],
) ),
) );
$body = curl_exec( $ch );
$code = (int) curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
$err = curl_errno( $ch );
curl_close( $ch );
// A connection error means the whole site is unreachable; stop hammering it.
if ( $err ) { return array( 'ok' => $ok, 'failed' => $failed, 'unreachable' => true ); }
200 === $code ? $ok++ : $failed++;
}
return array( 'ok' => $ok, 'failed' => $failed, 'unreachable' => false );
}
/** Fan the whole sheet out, printing one line per site. */
function te_fleet_push( array $sites, array $rows ): void {
$by_site = te_group_by_site( $rows );
$total_ok = 0; $reached = 0; $down = 0;
printf( "Reading %d changes from the sheet across %d sites...\n", count( $rows ), count( $by_site ) );
foreach ( $by_site as $site => $batch ) {
if ( ! isset( $sites[ $site ] ) ) { printf( " %-9s not in registry, skipped\n", $site ); continue; }
$r = te_push_site( $sites[ $site ], $batch );
$total_ok += $r['ok']; // rows that landed before a mid-batch drop still count
if ( $r['unreachable'] ) {
printf( " %-9s UNREACHABLE (connection refused) after %d updated\n", $site, $r['ok'] );
$down++;
} else {
printf( " %-9s %d updated, %d failed\n", $site, $r['ok'], $r['failed'] );
$reached++;
}
}
printf( "Done: %d updated across %d sites, %d site(s) unreachable.\n", $total_ok, $reached, $down );
}
// Read the sheet (website, post_id, title per row) and fan it out to the fleet.
$key = json_decode( file_get_contents( '/etc/te/sa-key.json' ), true );
$token = te_sheet_token( $key );
$rows = te_sheet_read( 'YOUR_SHEET_ID', 'Sheet1!A:C', $token );
$head = array_shift( $rows ); // drop the header row
$cols = array_flip( $head ); // map column name to index
$changes = array();
foreach ( $rows as $r ) {
$changes[] = array(
'website' => $r[ $cols['website'] ] ?? '',
'post_id' => $r[ $cols['post_id'] ] ?? '',
'title' => $r[ $cols['title'] ] ?? '',
);
}
te_fleet_push( $te_sites, $changes );The shared helpers call WordPress functions (wp_json_encode, wp_remote_post), so run the controller where WordPress is loaded, for example wp eval-file fleet-push.php against a WordPress install on the control machine. Run against the fleet, the output is one line per site:

Three rules make partial failure safe. Each site is independent: a failure on one never aborts the others. A connection error is the site, not the row: curl_errno set means the host did not answer, so skip the rest of that site; an HTTP 404 or 500 is a per-row failure on a site that is up. Fail fast on the dead one: a three-second CURLOPT_CONNECTTIMEOUT means one unreachable site costs three seconds, not thirty.
Put it on the control box's crontab through WP-CLI so the helpers have WordPress loaded (*/30 * * * * wp --path=/var/www/control eval-file /opt/te-fleet/fleet-push.php >/var/log/te-fleet.log 2>&1, where /var/www/control is any WordPress install on that machine). Past roughly twenty sites, or with far-away hosts, fire sites in parallel with curl_multi so the run takes as long as the slowest site rather than the sum. Keep secrets in the control machine's environment or a secrets manager so the registry in git holds only URLs and env-var names. If your sites are true WordPress Multisite (one installation, one wp-content), you need none of this: a network-activated plugin with a switch_to_blog() loop reaches every site directly.
Bulk-update custom fields from a Google Sheet
This is the pull model in its plainest form, and the engine under every recipe below: WordPress authenticates as the service account, reads the rows, compares each to what it already has, and writes only the rows that differ. No Apps Script, no button, and nobody in wp-admin.
| post_id | new_currency |
|---|---|
| 5001 | EUR |
| 5002 | EUR |
| 5003 | EUR |
| 5004 | EUR |
The command registers wp te-sheet pull and writes nothing unless you pass --live (include the shared helpers from the reading section at the top of the file):
<?php
/**
* Plugin Name: TE Sheet Pull
* Plugin URI: https://techearl.com/wordpress-update-from-google-sheet-rest-api
* Description: WP-CLI command that reads a Google Sheet via a service account and applies rows to WordPress.
* Author: Ishan Karunaratne
* Author URI: https://techearl.com
*/
defined( 'ABSPATH' ) || exit;
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) { return; }
// te_b64url(), te_sheet_token() and te_sheet_read() go here (see the reading section).
class TE_Sheet_Pull_Command {
/**
* Pull a sheet and apply a column to a post-meta key.
*
* ## OPTIONS
* --sheet=<id> : Spreadsheet ID.
* --key=<path> : Path to the service-account JSON key.
* --field=<key> : The post-meta key to write.
* [--range=<a1>] : Sheet range. Default: Sheet1!A:B
* [--live] : Actually write. Without it, dry run.
*/
public function pull( $args, $assoc ) {
$key = json_decode( file_get_contents( $assoc['key'] ), true );
$range = $assoc['range'] ?? 'Sheet1!A:B';
$field = $assoc['field'];
$live = isset( $assoc['live'] );
$token = te_sheet_token( $key );
if ( ! $token ) { WP_CLI::error( 'Could not get an access token.' ); }
$rows = te_sheet_read( $assoc['sheet'], $range, $token );
array_shift( $rows ); // drop the header row
$changes = array();
foreach ( $rows as $row ) {
$post_id = (int) ( $row[0] ?? 0 );
$value = (string) ( $row[1] ?? '' );
if ( ! $post_id || '' === $value ) { continue; }
$current = (string) get_post_meta( $post_id, $field, true );
if ( $current === $value ) { continue; } // change-only
$changes[] = array( 'post_id' => $post_id, 'old' => $current, 'new' => $value );
if ( $live ) { update_post_meta( $post_id, $field, $value ); }
}
if ( empty( $changes ) ) { WP_CLI::success( 'Sheet and WordPress already match.' ); return; }
WP_CLI\Utils\format_items( 'table', $changes, array( 'post_id', 'old', 'new' ) );
$mode = $live ? 'updated' : 'WOULD update (dry run)';
WP_CLI::success( sprintf( '%d posts %s from the sheet.', count( $changes ), $mode ) );
}
}
WP_CLI::add_command( 'te-sheet', 'TE_Sheet_Pull_Command' );Dry run first, then --live. The old column is what WordPress had, the new column is what the sheet says, and only differing rows appear, so a re-run right after changes nothing:

Query wp_postmeta afterwards and the value from the sheet is a real row on each post:

Put the command on a system crontab and the sheet becomes a live source of truth WordPress reconciles to. This lightweight command has dry-run and change-only but no backup or journal; for consequential writes, use the safe batch rails. If the field is an ACF field, write it with update_field (using the field key) rather than update_post_meta so the field reference stays correct, and plan a field-specific restore. For WooCommerce prices and stock, write through the CRUD (wc_get_product(), the setters, save()); the WooCommerce sheet updater covers that.
Bulk-edit SEO titles and meta descriptions from a sheet
Yoast and Rank Math both store the per-post SEO title and meta description as ordinary post meta and read them straight back on each render, so writing those keys from a sheet is exactly what the editor metabox does, for hundreds of posts at once.
| post_id | seo_title | meta_description |
|---|---|---|
| 4012 | Best Espresso Machines for 2022, Tested | I tested 14 home espresso machines for pressure, steam, and shot quality. Here are the six worth buying and the ones to skip. |
| 4013 | How to Descale an Espresso Machine (Step by Step) | Descaling an espresso machine in six steps, how often to do it, and the citric-acid ratio that will not wreck the seals. |
| 4014 | Espresso vs Drip Coffee: The Real Differences | Espresso and drip differ in grind, pressure, and extraction time. What that means for taste, caffeine, and your morning. |
The only plugin-specific part is the key names:
| What | Yoast SEO | Rank Math |
|---|---|---|
| SEO title | _yoast_wpseo_title | rank_math_title |
| Meta description | _yoast_wpseo_metadesc | rank_math_description |
| Focus keyword | _yoast_wpseo_focuskw | rank_math_focus_keyword |
Detect the active plugin at runtime so one command works across a fleet where some sites run Yoast and some Rank Math (the file needs require_once ABSPATH . 'wp-admin/includes/plugin.php'; for is_plugin_active() in a CLI context):
/** Return the [title_key, desc_key] meta keys for whichever SEO plugin is active. */
function te_seo_meta_keys() {
if ( defined( 'WPSEO_VERSION' ) || is_plugin_active( 'wordpress-seo/wp-seo.php' ) ) {
return array( '_yoast_wpseo_title', '_yoast_wpseo_metadesc' );
}
if ( class_exists( 'RankMath' ) || is_plugin_active( 'seo-by-rank-math/rank-math.php' ) ) {
return array( 'rank_math_title', 'rank_math_description' );
}
return array( '', '' ); // no supported SEO plugin detected
}The wp te-sheet seo command is the pull command with this per-row loop in place of the single-field one (range Sheet1!A:C, columns post_id, seo_title, meta_description):
list( $title_key, $desc_key ) = te_seo_meta_keys();
if ( '' === $title_key ) { WP_CLI::error( 'No supported SEO plugin (Yoast or Rank Math) is active.' ); }
foreach ( $rows as $row ) {
$post_id = (int) ( $row[0] ?? 0 );
if ( ! $post_id || 'publish' !== get_post_status( $post_id ) ) { continue; }
foreach ( array( array( $title_key, $row[1] ?? null, 'title' ), array( $desc_key, $row[2] ?? null, 'desc' ) ) as $field ) {
list( $meta_key, $new, $label ) = $field;
if ( null === $new || '' === trim( $new ) ) { continue; } // blank cell = leave alone
$new = trim( $new );
$current = (string) get_post_meta( $post_id, $meta_key, true );
if ( $current === $new ) { continue; } // change-only
$changes[] = array( 'post_id' => $post_id, 'field' => $label, 'old' => $current, 'new' => $new );
if ( $live ) { update_post_meta( $post_id, $meta_key, $new ); }
}
}A blank cell means "leave this field alone," not "set it to empty," so a row can carry only a new description without wiping the title. Clearing a field is a different intent and deserves its own explicit flag.

Three gotchas specific to SEO meta:
- A literal title overrides the template. Yoast's default title is a template like
%%title%% %%sep%% %%sitename%%. A literal string in_yoast_wpseo_titleis the per-post override and becomes the whole<title>, so you own the separator and brand. Put the variables in the cell if you want them expanded. Rank Math works the same way with its own%title%-style variables. Decide per column and be consistent. - Lengths are a hint. Aim for titles around 60 characters (Google truncates the title link around 580 pixels) and descriptions around 150 to 160. Google rewrites the displayed title and description for a meaningful share of results (a 2021 Google study put title rewrites in the low double-digit percentages; descriptions are rewritten more often), so you are advising the search engine, not configuring it.
- It is live immediately, except for caches. No re-save is needed; the plugin reads the key on every render. A full-page cache, CDN edge cache or persistent object cache can keep serving the old tags until purged. Purge the affected URLs and confirm with
curl -s https://example.com/the-post/ | grep -i '<title>'.
Keeping a human at the --live step is a feature here: SEO copy is editorial, and the dry-run table is the review. If you would rather set SEO titles with logic (a pattern across a post type) instead of data, filters do that in code: see overriding the SEO title and meta description.
Update a business directory from a Google Sheet
wp te-directory pull --sheet=YOUR_SHEET_ID \
--key=/srv/secrets/directory-sa.jsonA directory has more at stake than a single field, so this recipe ships as a complete downloadable directory-sync plugin with its own sheet reader. It matches a stable listing_id to an existing listing, validates the whole input range, and writes only changes. It previews by default; a live run requires a checked private database export, records its plan and attempts, and verifies each listing's title, metadata and open/closed terms. It handles at most 1,000 rows per range and fails before any write if validation or backup creation fails.
The download registers a public listing post type and a listing_status taxonomy, and owns four native text-meta keys: phone, address, hours (a JSON string) and permanently_closed, plus the post title from the name column. Install it on staging with that data model; if an existing directory plugin already owns the post type or fields, adapt its API instead. It needs PHP 8.1+, WP-CLI, PHP OpenSSL and a working wp db export:
wp plugin activate te-directory-sync
wp rewrite flushFlush rewrite rules once after registration, not on every import. Assign a unique listing_id to each listing first; the updater does not create missing listings or delete rows omitted from the sheet.
| listing_id | name | phone | address | hours | permanently_closed |
|---|---|---|---|---|---|
| L-1001 | Example Corner Cafe | +1 202-555-0101 | 10 Example Street | Mon-Fri 7:00-15:00; Sat-Sun 8:00-14:00 | no |
| L-1002 | Example Bookshop | +1 202-555-0102 | 12 Example Street | Mon-Sat 9:00-18:00 | no |
| L-1003 | Example Repair Shop | +1 202-555-0103 | 14 Example Street | closed | yes |
These rows are fictional examples. name is the desired title, not the lookup key, so a renamed business still resolves through listing_id. Duplicate IDs, multiple matching posts and unknown IDs stop the whole range before writes. The default range is Listings!A1:F1001. Blank phone/address cells clear those fields; blank hours preserve the old schedule; closed sets every day closed; permanently_closed accepts yes, no or blank. Agree these meanings with whoever maintains the sheet. The service-account key must sit outside every served directory with owner-only permissions, and the plugin rejects it otherwise. A failed request is an error, not an empty sheet.
Hours support one same-day interval per day, forward ranges like Mon-Fri, and 00:00 through 23:59. Every clause is validated before any listing changes:
$hours = te_directory_parse_hours( 'Mon-Fri 7:00-15:00; Sat-Sun 8:00-14:00' );
// $hours['mon'] is array( 'open' => '07:00', 'close' => '15:00' ).
$preserve = te_directory_parse_hours( '' ); // null: leave existing hours alone.
$closed = te_directory_parse_hours( 'closed' ); // Every day explicitly null.
// Each throws; none silently becomes an empty schedule:
// te_directory_parse_hours( 'Mon 25:00-26:00' );
// te_directory_parse_hours( 'Fri-Mon 9:00-17:00' );
// te_directory_parse_hours( 'Mon-Fri 9:00-17:00; Fri 10:00-18:00' );Overnight openings, split shifts, holiday exceptions and 24:00 are deliberately rejected, and these wall-clock strings do not implement "open now" without the listing's timezone and exception rules.
Closed, not deleted. permanently_closed = yes writes the flag and assigns the closed term; an open row gets the open term. The term is reconciled even if the flag already matches, so a prior partial write gets repaired. Your template still has to show the closure accurately and exclude closed places from open-business filters; do not publish a misleading active-business page to retain traffic.
A live run acquires a lock in the private backup directory, validates the sheet and existing field shapes, exports the database (--single-transaction --skip-lock-tables, so check your table engines), writes and syncs the full plan to a JSON-lines journal, then per listing rechecks, journals the attempt, applies, verifies and journals success. It also rejects metadata keys that differ only in case (Phone beside phone):
install -d -m 700 "$HOME/te-directory-backups"
wp te-directory pull --sheet=YOUR_SHEET_ID \
--key=/srv/secrets/directory-sa.json \
--backup-dir="$HOME/te-directory-backups" --liveIt is not a database transaction: a failure leaves earlier listings changed. Compare the plan, attempt records and current data, and recover from the recorded before-state. A whole-database rollback (wp db import /srv/private/ACTUAL_BACKUP_FILENAME.sql) replaces everything since the backup, so rehearse it on a copy with writers paused. A second successful run reports no changes, but that alone does not make unattended scheduling safe; add alerting and ownership first. Geocoding is a separate job: an address change can leave stored coordinates stale.
Manage a restaurant menu from a Google Sheet
The kitchen edits a sheet (prices, sections, a daily special, an 86'd flag) and WordPress reconciles a menu_item post type to it every few minutes.
| item_id | name | section | price | special | sold_out |
|---|---|---|---|---|---|
| BR-01 | Sourdough & Cultured Butter | Starters | 7.00 | no | no |
| MN-04 | Dry-Aged Ribeye, 300g | Mains | 38.50 | yes | no |
| MN-09 | Whole Roast Plaice | Mains | 26.00 | no | yes |
| DS-02 | Burnt Basque Cheesecake | Desserts | 9.00 | no | no |
Do not join on the dish name. "Ribeye" becomes "Dry-Aged Ribeye, 300g" becomes "Tomahawk for Two," and every rename would orphan a row and create a duplicate. A stable SKU-style item_id is assigned once, stored as meta on the post, and used for lookup. If you already have a menu plugin, reuse its post type; otherwise register one:
<?php
/** Register the menu_item post type. Runs on init. */
function te_register_menu_item_cpt() {
register_post_type( 'menu_item', array(
'labels' => array(
'name' => 'Menu Items',
'singular_name' => 'Menu Item',
),
'public' => true,
'show_in_rest' => true,
'menu_icon' => 'dashicons-food',
'supports' => array( 'title', 'editor', 'thumbnail' ),
'has_archive' => true,
'rewrite' => array( 'slug' => 'menu' ),
) );
}
add_action( 'init', 'te_register_menu_item_cpt' );The values are simple scalars, so native meta is enough; ACF earns its place if staff also edit dishes in wp-admin and want a friendly UI. Money is a string, not a number. A sheet will show 9.00 as 9 the moment the cell is a number format, and a float cast drops trailing zeros and turns 9.10 into 9.1. Format the price column as plain text in the sheet, and never cast it to (float) or (int) in the sync.
The wp te-menu pull command (range Menu!A:F) resolves each dish by item_id, never by title, and maps the row to four meta values:
/** Resolve a menu_item post by its stable item_id, never by title. */
private function te_find_by_item_id( $item_id ) {
$found = get_posts( array(
'post_type' => 'menu_item',
'post_status' => 'any',
'numberposts' => 1,
'fields' => 'ids',
'meta_key' => 'item_id',
'meta_value' => $item_id,
) );
return $found ? (int) $found[0] : 0;
}
// Inside pull(), per row, after resolving $post_id (warn and skip when it is 0):
// The sheet is semi-trusted input, so sanitize every free-text value on
// the way in (sanitize_text_field leaves a price like "9.00" untouched).
// Price stays a string. Never cast to float.
$want = array(
'price' => sanitize_text_field( (string) ( $row[3] ?? '' ) ),
'section' => sanitize_text_field( (string) ( $row[2] ?? '' ) ),
'is_special' => strtolower( trim( (string) ( $row[4] ?? '' ) ) ) === 'yes' ? '1' : '0',
'is_86' => strtolower( trim( (string) ( $row[5] ?? '' ) ) ) === 'yes' ? '1' : '0',
);
// Then the same change-only loop: compare each to get_post_meta(), log old to new,
// and update_post_meta() only with --live.86'd means hide, not delete. The dish is coming back tomorrow, and deleting it throws away its ID, the item_id link, its photo and its URL. The sync writes an is_86 flag and the theme decides:
<?php
/** In the menu template loop: skip or mark an 86'd dish. */
$is_86 = get_post_meta( get_the_ID(), 'is_86', true );
if ( $is_86 ) {
// Option A: hide it completely from today's menu.
// continue;
// Option B: keep it visible but greyed out and unorderable.
echo '<li class="menu-item is-sold-out">';
echo '<span class="dish">' . esc_html( get_the_title() ) . '</span>';
echo '<span class="badge">Sold out</span>';
echo '</li>';
}is_special works the same way for a "Chef's special" ribbon. Escape every sheet value on output too (esc_html around the section and price): whoever can edit the sheet can write what lands on the page.

Because the sync is change-only, running it every three minutes is cheap:
# Every 3 minutes, reconcile the menu from the sheet.
*/3 * * * * cd /var/www/site && wp te-menu pull --sheet=SHEET_ID --key=/etc/secrets/menu-sa.json --live >> /var/log/te-menu.log 2>&1One gap in a pure pull: if a manager 86's a dish inside wp-admin, the sheet still says sold_out = no and the next pull un-86's it. Close it with the two-way sync: the sheet owns price, section and special, and the is_86 flag is written back to the sheet so both sides agree. For online ordering in WooCommerce, use item_id as the SKU, resolve it with wc_get_product_id_by_sku(), and set the price through set_regular_price('38.50') and save().
Populate an events calendar from a Google Sheet
Keep one row per event keyed by a stable event_id, pull it on a cron, store each date as a sortable Y-m-d H:i:s string in the site's timezone, and apply only changed rows. New rows appear as posts and the sold-out badge flips when the flag flips.
| event_id | title | start | end | venue | sold_out | tickets_url |
|---|---|---|---|---|---|---|
| EV-1001 | Spring Synth Night | 2022-05-14 20:00 | 2022-05-14 23:30 | The Glasshouse | no | https://tix.example/ev-1001 |
| EV-1002 | Saturday Matinee | 2022-05-21 14:00 | 2022-05-21 16:00 | The Glasshouse | yes | https://tix.example/ev-1002 |
| EV-1003 | Late Jazz Session | 2022-06-04 21:00 | 2022-06-05 00:30 | Cellar Room | no | https://tix.example/ev-1003 |
EV-1003 ends after midnight, which is why you store a real datetime and not just a date. The store is a plain event post type:
<?php
add_action( 'init', 'te_register_event_cpt' );
function te_register_event_cpt() {
register_post_type( 'event', array(
'label' => 'Events',
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-calendar-alt',
'supports' => array( 'title', 'editor', 'thumbnail' ),
'rewrite' => array( 'slug' => 'events' ),
) );
}Dates and timezone. Store two things per start: a normalized Y-m-d H:i:s string (it sorts lexically in chronological order) and a Unix timestamp for numeric range maths. "8pm" in the sheet means 8pm in the site's timezone, so parse against wp_timezone(), never PHP's default zone:
/** Parse a human "Y-m-d H:i" from the sheet into the site timezone. Returns a DateTimeImmutable or null. */
function te_parse_event_datetime( $raw ) {
$raw = trim( (string) $raw );
if ( '' === $raw ) { return null; }
$tz = wp_timezone();
$dt = date_create_immutable( $raw, $tz );
return $dt ?: null;
}
/** A human yes/no from the sheet, as a clean boolean. */
function te_truthy( $raw ) {
return in_array( strtolower( trim( (string) $raw ) ), array( 'yes', 'y', 'true', '1', 'sold out', 'sold' ), true );
}getTimestamp() returns the absolute instant regardless of zone, and the string stays local on purpose so the calendar shows the time the event starts in its own city. The wp te-events pull command (range Events!A:G) maps each row to these fields:
$fields = array(
'event_start' => $start->format( 'Y-m-d H:i:s' ),
'event_end' => $end ? $end->format( 'Y-m-d H:i:s' ) : '',
'event_start_ts' => (string) $start->getTimestamp(),
'event_venue' => sanitize_text_field( (string) ( $row[4] ?? '' ) ),
'event_sold_out' => te_truthy( $row[5] ?? '' ) ? '1' : '0',
'event_tickets' => esc_url_raw( trim( (string) ( $row[6] ?? '' ) ) ),
);Unlike the menu, events can be created from the sheet, so the command finds an event by event_id, diffs only what changed, and inserts or updates:
function te_find_event_by_id( $event_id ) {
$found = get_posts( array(
'post_type' => 'event',
'post_status' => 'any',
'numberposts' => 1,
'fields' => 'ids',
'meta_key' => 'event_id',
'meta_value' => $event_id,
) );
return $found ? (int) $found[0] : 0;
}
function te_event_diff( $post_id, $title, array $fields ) {
$diff = array();
if ( ! $post_id ) { return array( 'title' => $title ) + $fields; } // new event: everything changes
if ( get_the_title( $post_id ) !== $title ) { $diff['title'] = $title; }
foreach ( $fields as $k => $v ) {
if ( (string) get_post_meta( $post_id, $k, true ) !== (string) $v ) { $diff[ $k ] = $v; }
}
return $diff;
}
function te_apply_event( $post_id, $event_id, $title, array $fields ) {
$post_id = wp_insert_post( array(
'ID' => $post_id ?: 0,
'post_type' => 'event',
'post_status' => 'publish',
'post_title' => $title,
) );
update_post_meta( $post_id, 'event_id', $event_id );
foreach ( $fields as $k => $v ) {
update_post_meta( $post_id, $k, $v );
}
}
The sold-out badge is one line in the single-event template:
if ( get_post_meta( get_the_ID(), 'event_sold_out', true ) ) {
echo '<span class="event-badge event-badge--sold-out">Sold out</span>';
}"Upcoming, soonest first" in the theme compares against current_time('mysql'), which is "now" in the site timezone in the same format the meta was stored in. Set DATETIME on both the sort and the comparison so MySQL casts the meta to a real datetime:
$now = current_time( 'mysql' ); // 'Y-m-d H:i:s' in the site timezone
$upcoming = new WP_Query( array(
'post_type' => 'event',
'posts_per_page' => 10,
'meta_key' => 'event_start',
'orderby' => 'meta_value',
'meta_type' => 'DATETIME',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'event_start',
'value' => $now,
'compare' => '>=',
'type' => 'DATETIME',
),
),
) );If you run The Events Calendar, do not invent a CPT: point the importer at tribe_events and write the local-time Y-m-d H:i:s string to _EventStartDate and _EventEndDate (the plugin keeps _EventStartDateUTC / _EventEndDateUTC companions), still parsed against wp_timezone(), and keep your own event_id meta as the join key. Schedule it nightly from system cron:
# crontab: reconcile the calendar from the sheet every night at 02:15
15 2 * * * cd /var/www/site && wp te-events pull --sheet=SHEET_ID --key=/etc/te/sa-key.json --live >> /var/log/te-events.log 2>&1The pull never retires anything on its own. To take ended events off the calendar, run the upcoming query with the comparison flipped and move the matches to a status your theme already hides, such as draft, rather than deleting them (the post keeps its URL history and its event_id):
function te_retire_past_events() {
$ended = get_posts( array(
'post_type' => 'event',
'post_status' => 'publish',
'numberposts' => -1,
'fields' => 'ids',
'meta_query' => array(
array(
'key' => 'event_end',
'value' => current_time( 'mysql' ),
'compare' => '<',
'type' => 'DATETIME',
),
),
) );
foreach ( $ended as $post_id ) {
wp_update_post( array( 'ID' => $post_id, 'post_status' => 'draft' ) );
}
return count( $ended );
}Events with an empty event_end are skipped by that comparison, so give single-day events an end time in the sheet if you want them retired.
Set featured images from a spreadsheet of URLs
A sheet of post_id and image_url becomes featured images with two calls per row: sideload the URL into the media library to get an attachment ID, then set it as the thumbnail. The extra moving part, compared with every other recipe here, is that WordPress fetches a binary file from the internet, which is where idempotency and security bite.
$attachment_id = media_sideload_image( $url, $post_id, $desc, 'id' );
if ( ! is_wp_error( $attachment_id ) ) {
set_post_thumbnail( $post_id, $attachment_id );
}Pass 'id' as the fourth argument: the default return is an HTML <img> tag (the other accepted value is 'src'). A failed download returns a WP_Error, so always guard.
Load the admin includes in WP-CLI. media_sideload_image() lives in wp-admin/includes/media.php, which WordPress only loads for admin pages. In a WP-CLI command or cron callback you get Call to undefined function media_sideload_image() unless you require all three files: media.php declares the function, file.php provides download_url(), and image.php provides the metadata and thumbnail-size helpers.
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';Idempotency, or you download everything twice. media_sideload_image() has no memory: call it twice and you get a second attachment and an orphaned first one. Guard it two ways: skip posts where has_post_thumbnail() is already true (a fill-the-gaps default), and store the sideloaded URL in a te_featured_src meta key so an unchanged URL is skipped while a changed one is applied.
SSRF guard. The fetch is server-side, and media_sideload_image() does not block private or internal addresses on its own (WordPress only validates URLs when a request opts into reject_unsafe_urls, and this path does not). A sheet a content editor can change could otherwise point your server at http://169.254.169.254/ (cloud instance metadata) or an internal admin service. Pin the hosts you actually serve images from. The core of wp te-sheet featured (with a --force flag to replace existing thumbnails):
// SSRF guard. media_sideload_image() fetches the URL server-side, and WordPress
// does NOT block private/internal addresses by default, so an arbitrary URL from
// a sheet anyone can edit is a server-side request forgery vector. Pin the hosts
// you actually serve images from.
const TE_IMG_HOSTS = array( 'cdn.example.com', 'assets.example.com' );
function te_host_allowed( string $src ): bool {
$parts = wp_parse_url( $src );
return 'https' === ( $parts['scheme'] ?? '' )
&& in_array( strtolower( $parts['host'] ?? '' ), TE_IMG_HOSTS, true );
}
// Inside featured(), per row:
$post_id = (int) ( $row[0] ?? 0 );
$src = trim( (string) ( $row[1] ?? '' ) );
if ( ! $post_id || '' === $src || ! get_post( $post_id ) ) { continue; }
// SSRF guard: refuse any URL not on the trusted-host allowlist.
if ( ! te_host_allowed( $src ) ) {
WP_CLI::warning( sprintf( 'Post %d: refused non-allowlisted image host (%s)', $post_id, $src ) );
continue;
}
// Idempotency guard: same source already applied means nothing to do.
$applied = (string) get_post_meta( $post_id, 'te_featured_src', true );
if ( $applied === $src ) { continue; }
// Default to a fill-the-gaps job: leave existing thumbnails alone unless --force.
$status = 'set from sheet';
if ( ! $force && has_post_thumbnail( $post_id ) ) {
continue;
}
if ( has_post_thumbnail( $post_id ) ) { $status = 'replaced (--force)'; }
$changes[] = array( 'post_id' => $post_id, 'image_url' => $src, 'action' => $status );
if ( $live ) {
$attachment_id = media_sideload_image( $src, $post_id, null, 'id' );
if ( is_wp_error( $attachment_id ) ) {
WP_CLI::warning( sprintf( 'Post %d: %s', $post_id, $attachment_id->get_error_message() ) );
array_pop( $changes );
continue;
}
set_post_thumbnail( $post_id, $attachment_id );
update_post_meta( $post_id, 'te_featured_src', $src );
}The null third argument is the description (title and alt default from the filename; pass a real string if your sheet has an alt-text column). array_pop() un-records a row whose download failed so the count stays honest.

Sideloaded images are normal attachments: they land in wp-content/uploads/, show up in Media, get rebuilt by wp media regenerate, and are linked through the same _thumbnail_id key the editor's Featured Image panel sets. The WordPress server must be able to reach each URL (a URL behind a VPN or on localhost fails with a logged warning), and each download plus resizing is real time and memory, so chunk a few thousand rows using the WP-CLI batching practices.
For WooCommerce product images, sideload the same way but hand the IDs to the product object rather than writing _thumbnail_id:
$product = wc_get_product( $post_id ); // or wc_get_product_id_by_sku( $sku )
$main_id = media_sideload_image( $main_url, $post_id, null, 'id' );
if ( ! is_wp_error( $main_id ) ) {
$product->set_image_id( $main_id );
}
$gallery_ids = array();
foreach ( $gallery_urls as $g_url ) {
$g_id = media_sideload_image( $g_url, $post_id, null, 'id' );
if ( ! is_wp_error( $g_id ) ) { $gallery_ids[] = $g_id; }
}
if ( $gallery_ids ) { $product->set_gallery_image_ids( $gallery_ids ); }
$product->save();A natural sheet for that has a sku column, a main_image_url and a pipe-separated gallery_image_urls cell, with the same te_featured_src guard on the main image.
onEdit runs in a restricted context that cannot call UrlFetchApp, so the request never goes out. Rename the handler and register it as an installable On edit trigger under Triggers.update_post_meta in the handler, or use the server-side pull. For ACF use update_field; for WooCommerce use the CRUD (wc_get_product, set_regular_price, save) so caches and lookup tables stay correct.spreadsheets scope and an Editor share to write back.wp-content), use a network-activated plugin with a switch_to_blog() loop instead; no HTTP calls needed.update_post_meta is doing by hand what the plugin does on save, and the change is live on the next uncached render.date_create_immutable( $raw, wp_timezone() ) so the wall-clock time is anchored to the site's configured timezone; otherwise PHP uses its own default zone (often UTC) and stores the wrong instant.media_sideload_image() lives in wp-admin/includes/media.php, which WordPress only loads for admin pages. Require media.php, file.php and image.php from ABSPATH . 'wp-admin/includes/' before the first call.Sources
Authoritative references this article was fact-checked against.
- register_rest_route() - WordPress Developer Referencedeveloper.wordpress.org
- Adding Custom Endpoints - WordPress REST API Handbookdeveloper.wordpress.org
- UrlFetchApp - Google Apps Script Referencedevelopers.google.com
- hash_equals - PHP Manualphp.net
- wp_update_post() - WordPress Developer Referencedeveloper.wordpress.org
- WP_REST_Request::get_param() - WordPress Developer Referencedeveloper.wordpress.org
- Authentication (Application Passwords) - WordPress REST API Handbookdeveloper.wordpress.org
- Quotas for Google Services - Apps Scriptdevelopers.google.com
- Publish a file to the web - Google Docs Editors Helpsupport.google.com
- spreadsheets.values.get - Google Sheets APIdevelopers.google.com
- str_getcsv - PHP Manualphp.net
- OAuth 2.0 for service accounts - Google Identitydevelopers.google.com
- openssl_sign - PHP Manualphp.net
- wp_remote_post() - WordPress Developer Referencedeveloper.wordpress.org
- wp_remote_get() - WordPress Developer Referencedeveloper.wordpress.org
- update_post_meta() - WordPress Developer Referencedeveloper.wordpress.org
- get_post_meta() - WordPress Developer Referencedeveloper.wordpress.org
- wp_slash: preserving literal metadata stringsdeveloper.wordpress.org
- PHP fsync: synchronizing file contentsphp.net
- WP-CLI Commands - WP-CLI Command Referencedeveloper.wordpress.org
- WP_CLI::add_command() - WP-CLI Handbookmake.wordpress.org
- WP_CLI\Utils\format_items() - WP-CLI Handbookmake.wordpress.org
- WP_CLI::runcommand return codesmake.wordpress.org
- wp db export - WP-CLI Command Referencedeveloper.wordpress.org
- Installable Triggers - Google Apps Scriptdevelopers.google.com
- Simple Triggers - Google Apps Scriptdevelopers.google.com
- spreadsheets.values.batchUpdate - Google Sheets APIdevelopers.google.com
- ValueInputOption (RAW vs USER_ENTERED) - Google Sheets APIdevelopers.google.com
- Usage Limits - Google Sheets APIdevelopers.google.com
- wp eval-file - WP-CLI command referencedeveloper.wordpress.org
- Hooking WP-Cron Into the System Task Scheduler - WordPress Plugin Handbookdeveloper.wordpress.org
- curl_multi_init - PHP Manualphp.net
- register_post_type() - WordPress Developer Referencedeveloper.wordpress.org
- wp_set_object_terms: taxonomy changes and errorsdeveloper.wordpress.org
- wp_timezone() - WordPress Developer Referencedeveloper.wordpress.org
- WP_Query orderby and meta_query parameters - WordPress Developer Referencedeveloper.wordpress.org
- media_sideload_image() - WordPress Developer Referencedeveloper.wordpress.org
- set_post_thumbnail() - WordPress Developer Referencedeveloper.wordpress.org
- has_post_thumbnail() - WordPress Developer Referencedeveloper.wordpress.org





