Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 68 ยท Practice and Review

WordPress Cheat Sheet

A compact WordPress cheat sheet: template tags, conditional tags, core hooks, WP_Query arguments, post type and taxonomy options, escaping, WP-CLI and theme.json keys.

This is the page to keep open in a second tab while you work. It does not teach; it reminds. Every entry points back to a lesson when you need the full story. The tables follow WordPress 6.x with block themes in mind, and they are deliberately short: only the names you reach for every week.

Because real WordPress cannot run on this site, the two runnable examples at the end are plain-PHP stand-ins: a small lookup tool for entries like these, and a demo of picking the right escaping function for each output context. Everything in the tables is read-only reference.

flowchart LR
    R["Request"] --> P["plugins_loaded"]
    P --> T["after_setup_theme"]
    T --> I["init"]
    I --> Q["pre_get_posts<br/>main query"]
    Q --> TR["template_redirect"]
    TR --> H["wp_head"]
    H --> B["page body"]
    B --> F["wp_footer"]
    F --> S["shutdown"]

The front-end order of the hooks you meet most often. Admin requests add admin_init and admin_menu.

Template tags

Tags starting with the_ print; most have a get_the_ twin that returns the value. See The Loop and Template Parts and Template Tags.

Tag What it gives you
the_title() / get_the_title() The post title
the_content() Post content, with filters applied
the_excerpt() The excerpt, or a trimmed content summary
the_permalink() / get_permalink() The post URL
the_post_thumbnail( $size ) The featured image as an img tag
the_date() / get_the_date() The publish date
the_author() The author's display name
the_category() / the_tags() Category and tag links
bloginfo( 'name' ) Site title (also description, url, charset)
home_url( $path ) / site_url() Site address / WordPress address
get_template_directory_uri() URL of the active (parent) theme folder
get_stylesheet_directory_uri() URL of the active (child) theme folder
get_header() / get_footer() / get_sidebar() Load header.php, footer.php, sidebar.php
get_template_part( $slug, $name, $args ) Load a reusable template file
wp_head() / wp_footer() Required in classic themes so assets and hooks print
body_class() / post_class() CSS classes for body and each post
wp_nav_menu( $args ) Print a registered menu
the_posts_pagination() Pagination links for an archive

Conditional tags

Tag True when
is_front_page() The site's front page (static page or posts)
is_home() The posts index (the blog)
is_singular() Any single post, page or custom post type
is_single() / is_page() A single post / a page
is_archive() Any archive: date, author, category, tag, taxonomy, post type
is_category() / is_tag() / is_tax() A category / tag / custom taxonomy archive
is_post_type_archive() A custom post type archive
is_author() / is_search() / is_404() Author archive / search results / not found
is_main_query() Inside the main query only
is_admin() Admin screens (also true for admin-ajax.php)
is_user_logged_in() A user is logged in

Core hooks

See Core Hooks You Will Use and How WordPress Handles a Request.

Hook Type Use it to
plugins_loaded action Boot a plugin once all plugins are loaded
after_setup_theme action Declare theme support, menus, image sizes
init action Register post types, taxonomies, shortcodes
wp_loaded action Run code after WordPress is fully loaded
pre_get_posts action Change a query before it runs
template_redirect action Redirect or choose behavior before output
wp_enqueue_scripts action Enqueue front-end styles and scripts
admin_enqueue_scripts action Enqueue admin assets
admin_menu action Add admin menu pages
admin_init action Register settings, handle admin-only setup
rest_api_init action Register REST routes
save_post action React when a post is saved
wp_footer action Print markup or scripts at the end of the page
the_content filter Change post content on output
the_title filter Change a title on output
body_class filter Add or remove body classes
template_include filter Swap the template file that will load
upload_mimes filter Allow or restrict upload types

Registering: add_action( $hook, $callback, $priority = 10, $accepted_args = 1 ) and add_filter( ... ). Lower priority runs first. Filters must return the value. Remove with the same callback and priority: remove_action( $hook, $callback, $priority ). See Actions and Filters.

WP_Query arguments

See WP_Query in Depth and Meta Queries and Taxonomy Queries.

Argument Meaning
post_type One type or an array of types
post_status publish, draft, any, ...
posts_per_page How many; -1 means all (use with care)
paged Page number for pagination
orderby / order date, title, menu_order, rand, meta_value_num, ... / ASC or DESC
s Search keyword
author / author_name Author ID or login name
cat / category_name / tag Core taxonomy shortcuts
tax_query Array of taxonomy clauses
meta_key / meta_value Simple meta filter (and the sort key)
meta_query Array of meta clauses with key, value, compare, type
date_query Date conditions (after, before, year, ...)
post__in / post__not_in Include or exclude by IDs
post_parent Children of a post (hierarchical types)
ignore_sticky_posts Do not move sticky posts to the top
fields ids returns only IDs
no_found_rows Skip the total count when you do not paginate
update_post_meta_cache Set to false if you do not read meta

After a custom loop, call wp_reset_postdata().

Post type and taxonomy arguments

See Custom Post Types and Custom Taxonomies. Register both on the init hook.

register_post_type() argument Meaning
labels Admin and menu wording
public Show in the front end and admin by default
show_in_rest Required for the block editor and the REST API
has_archive Enable an archive page (true or a slug)
rewrite URL slug and options, for example [ 'slug' => 'books' ]
supports title, editor, thumbnail, excerpt, custom-fields, ...
hierarchical Parent and child relationships, like pages
menu_icon / menu_position Admin menu icon (Dashicon) and position
capability_type / map_meta_cap Capability mapping
taxonomies Attach existing taxonomies
template Default blocks for new items

The key is at most 20 characters of lowercase letters, digits, underscores and dashes.

register_taxonomy() argument Meaning
first two arguments Taxonomy key, and the post type or array of types
hierarchical true behaves like categories, false like tags
labels / public Wording / visibility
show_in_rest Needed for the block editor panel
show_admin_column Add a column to the list table
rewrite URL structure
default_term Term assigned when none is chosen

Escaping and sanitizing

Escape late, in the right context; sanitize on input. See Escaping Output and Sanitizing and Validating Input.

Where the value goes Use
Text inside an HTML element esc_html()
An HTML attribute value esc_attr()
href or src esc_url()
A textarea body esc_textarea()
Post-like HTML you allow wp_kses_post() or wp_kses( $html, $allowed )
JSON in a script wp_json_encode() (and wp_add_inline_script())
Translated text, escaped esc_html__(), esc_attr__(), esc_html_e()
Input kind Sanitize with
Single-line text sanitize_text_field()
Multi-line text sanitize_textarea_field()
Email sanitize_email() (check with is_email())
Positive integer absint()
Slug sanitize_title()
Option or meta key sanitize_key()
File name sanitize_file_name()
URL to store or redirect to esc_url_raw()
Slashed $_POST data wp_unslash() first, then sanitize

Forms: wp_nonce_field( $action, $name ) to print, wp_verify_nonce() or check_admin_referer() to check. Then check the user: current_user_can( 'edit_post', $post_id ). SQL: $wpdb->prepare( 'SELECT ... WHERE id = %d AND name = %s', $id, $name ). See Forms and Nonces and Users, Roles and Capabilities.

WP-CLI

Run these in the site folder. See WP-CLI.

Terminal
wp core download                         # download WordPress
wp config create --dbname=wp --dbuser=root --prompt=dbpass
wp core install --url=http://example.test --title="Demo" \
  --admin_user=admin --admin_email=me@example.test
wp core update                           # update WordPress

wp plugin list                           # installed plugins
wp plugin install query-monitor --activate
wp plugin deactivate some-plugin
wp theme list
wp theme activate twentytwentyfive

wp post list --post_type=page            # list content
wp post create --post_title="Hello" --post_status=publish
wp user create editor1 editor1@example.test --role=editor
wp option get blogname                   # read and write options
wp option update blogdescription "Just testing"

wp db export backup.sql                  # back up the database
wp search-replace 'http://old.test' 'http://new.test' --dry-run
wp rewrite flush                         # rebuild permalink rules
wp cache flush                           # clear the object cache
wp cron event list                       # scheduled tasks
wp cron event run --due-now
wp eval 'echo get_bloginfo( "name" );'   # run PHP in WordPress

theme.json keys

See theme.json, Block Theme Basics and Style Variations, Fonts and Design Tokens.

Key Purpose
$schema, version Schema URL for editor help; schema version (3)
settings.appearanceTools Turn on a set of design controls at once
settings.color.palette Named colors; also gradients, custom, defaultPalette
settings.typography.fontFamilies / fontSizes Font stacks and size presets (with fluid sizes)
settings.spacing.spacingSizes Spacing scale presets; also units, padding, margin, blockGap
settings.layout.contentSize / wideSize Content and wide widths
settings.custom Your own design tokens
styles.color / typography / spacing Global styles
styles.elements Styles for link, button, heading, h1 to h6, ...
styles.blocks Styles per block, for example core/button
styles.css Extra CSS as a string
templateParts / customTemplates Register parts and custom templates

Presets become CSS custom properties named --wp--preset--{type}--{slug}, for example --wp--preset--color--primary. Entries under settings.custom become --wp--custom--*.

Try it: a tiny cheat sheet lookup

The first example stores a few entries like the tables above and searches them by keyword, the way a quick-reference tool would.

PHP Search a mini cheat sheet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Try it: pick the escaping function by context

The second example prints the same awkward value in five contexts. These are stand-ins for esc_html(), esc_attr(), esc_url(), esc_textarea() and wp_json_encode(); the real functions have more features, but the principle (one function per context) is the same.

PHP One value, five contexts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The JSON stand-in sets the JSON_HEX_* flags so that </script> cannot end the surrounding script block. When you use real WordPress, wp_add_inline_script() and wp_localize_script() handle this for you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function do you use to print a value inside a quoted HTML attribute?

    esc_attr() escapes the characters that could end or break an attribute value. esc_html() targets text nodes, esc_url_raw() is for storing URLs, and sanitize_text_field() cleans input rather than escaping output.
  2. 2. A post type key may be at most how long?

    The post type key is limited to 20 characters of lowercase letters, digits, underscores and dashes.
  3. 3. Which hook is the right place to call register_post_type()?

    Post types and taxonomies are registered on init, which runs on every request, front end and admin.
  4. 4. What does the WP_Query argument no_found_rows => true save?

    Without it, WordPress runs an extra count to fill found_posts and max_num_pages. Skip it when you do not paginate.

Summary

  • Template tags starting with the_ print and get_the_ returns; conditional tags decide which markup to show.
  • Register code on the right hook: init for types and shortcodes, wp_enqueue_scripts for assets, pre_get_posts for queries.
  • WP_Query has arguments for almost everything; no_found_rows and fields are quick performance wins.
  • Escape per output context, sanitize on input, bind SQL values, verify nonces and check capabilities.
  • WP-CLI covers install, content, options, backups and search-replace from the terminal.
  • theme.json presets become --wp--preset--* CSS variables.

Put this sheet to work with the WordPress Exercises with Solutions.