PHP › WordPress Plugin & Theme Development

Why is properly sanitizing input and escaping output especially critical in WordPress plugin and theme development, and what built in WordPress functions help with this?

Intermediate

Answer

Since WordPress plugins and themes are extremely widely used, running on a very large percentage of all websites, a security vulnerability discovered in a single popular plugin can potentially affect an enormous number of individual websites simultaneously, making rigorous input sanitization and output escaping especially critical, and WordPress provides a set of dedicated built in functions specifically for this purpose, such as sanitize_text_field for cleaning a piece of submitted text input, and esc_html for safely escaping a piece of text immediately before it is displayed within HTML output.
$name = sanitize_text_field($_POST['name']);
echo '<p>Hello, ' . esc_html($name) . '</p>';
Real-world example A WordPress contact form plugin sanitizes every submitted field using sanitize_text_field before saving it, and separately escapes that same data using esc_html immediately before displaying it back anywhere on the page, protecting against both malicious stored data and cross site scripting.

Common follow-ups: What is the difference between sanitizing input and escaping output, and why are both steps genuinely necessary?;What other specific sanitization and escaping functions does WordPress provide for different types of data, such as URLs or email addresses?