Working with Data

Work with arrays, JSON, serialized options and dates in WordPress without data that breaks after a migration.

A domain change, a search-replace, and half the settings are gone. Serialized strings store their length, a plain replace breaks it, and WordPress quietly returns false. This module covers the data WordPress keeps everywhere: arrays, JSON, serialized options, dates and strings.

CoursePHP for WordPress Developers · Module 7 of 9 · Stage 3 "Production code"
LearnArrays and wp_parse_args(), JSON and serialization, dates with time zones, multibyte strings
HowShort lessons with code from real plugins, IDE practice in the browser, interview questions after every lesson

The idea in one picture

flowchart LR
  A["Array in PHP"] --> S["maybe_serialize()<br/>s:4:#quot;test#quot;"]
  S --> D[("wp_options")]
  D --> U["maybe_unserialize()"]
  D -. "plain search-replace" .-> X["length mismatch<br/>returns false"]
  classDef step fill:#f5f3ff,stroke:#777BB4,color:#1e1b4b
  classDef key fill:#777BB4,stroke:#4f5b93,color:#ffffff

Serialized data knows its own length. Change the text without the length and it no longer unserializes.

Before → after

BeforeAfter Module 7
Defaults merged by handwp_parse_args()
A plain SQL replace on serialized optionswp search-replace, which handles serialization
date() in the server time zonewp_date() and DateTimeImmutable
strlen() on Ukrainian textmb_strlen() and other multibyte functions

You'll be able to answer

  • Why does a plain search-replace break serialized data?
  • When do you store JSON and when serialized arrays?
  • How do you handle time zones in WordPress?