Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 68 ยท Practice and Review

WordPress Exercises with Solutions

Eight graded WordPress exercises with solutions: hooks, the loop, queries, post types, shortcodes, nonces, sanitizing and capabilities, built as runnable PHP stand-ins.

You learn WordPress by wiring things together, and by getting them subtly wrong first. Reading about priorities, nonces or esc_html() is not the same as writing the code that makes them work. This page gives you eight exercises that cover the core ideas of the course: hooks, the loop, queries, custom post types, shortcodes, nonces, sanitizing and escaping, and capabilities.

A real WordPress site cannot run on this page, so every exercise uses a plain-PHP stand-in: a few lines that behave like the WordPress function you would call in a real project. You write the function body, the tests call it, and the output shows whether you got it right. What you build here is the idea behind the real function, not core's actual source. Where a real WordPress function differs from our stand-in, the solution says so.

How to use the page:

  • Each exercise has an editor with starter code that runs as given. The part you replace sits between the // --- your code --- and // --- tests --- comment lines. The comments in the tests show the output you should see.
  • Try first, peek later. Open the solution only after a real attempt.
  • Compare, don't copy. Your version may differ and still be right. Check that it passes the tests, then read ours for ideas.
  • Our PHP reports every error level, so a warning such as "Undefined array key" is a bug to fix, not noise.
flowchart LR
    I["Request data"] --> V["Validate and sanitize<br/>on the way in"]
    V --> C["Check nonce and<br/>capability"]
    C --> S["Store or query"]
    S --> E["Escape on the way out"]
    E --> O["HTML response"]

Several exercises below cover one stage each of this path: the safe journey of data through a WordPress feature.

Hooks

Hooks are the backbone of WordPress. These exercises cover actions and filters and priorities.

1. A filter chain with priorities (Beginner)

Callbacks are registered in $filters[$hook][$priority][]. Write apply_filters( $hook, $value ): it runs the callbacks from the lowest priority number to the highest, passing each result into the next callback, and returns the final value. A hook with no callbacks returns the value unchanged.

PHP Exercise 1: apply_filters

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.

Show solution
PHP
function apply_filters(string $hook, mixed $value): mixed
{
    global $filters;
    $byPriority = $filters[$hook] ?? [];
    ksort($byPriority);
    foreach ($byPriority as $callbacks) {
        foreach ($callbacks as $cb) {
            $value = $cb($value);
        }
    }
    return $value;
}

ksort() turns the priority keys into ascending order, so trim (5) runs before strtoupper (10) and the exclamation mark (20). Callbacks that share a priority keep their registration order, because they were appended to the same inner array. Real WordPress also supports accepted_args, removal and callback IDs; see Priorities, Order and Removing Hooks.

The loop and queries

These practice the loop and WP_Query.

2. Your own have_posts() and the_post() (Beginner)

The loop works because two functions share a position in a global query object. have_posts() says whether another post is waiting; the_post() advances the position and sets the global $post to that post. Implement both. The index starts at -1, meaning "before the first post".

PHP Exercise 2: have_posts and the_post

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.

Show solution
PHP
function have_posts(): bool
{
    global $wp_query;
    return $wp_query['index'] + 1 < count($wp_query['posts']);
}

function the_post(): void
{
    global $wp_query, $post;
    $wp_query['index']++;
    $post = $wp_query['posts'][$wp_query['index']];
}

have_posts() only looks; it never moves. That is why if ( have_posts() ) followed by while ( have_posts() ) works: the first call does not consume anything. Real WordPress also fires the loop_start and loop_end actions and calls setup_postdata() so template tags like the_title() can read the global.

3. Turn query arguments into safe SQL (Intermediate)

Write build_query( array $args ): array returning [ $sql, $params ] for a tiny WP_Query over SQLite. Support post_type (default post), s (title search), author, orderby (date or title, default date), order (ASC or DESC, default DESC) and posts_per_page (default 10). Only published posts are returned. User values must go in as bound parameters; the column and direction must come from a whitelist, because they cannot be bound.

PHP Exercise 3: build_query

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.

Show solution
PHP
function build_query(array $args): array
{
    $where = ["post_status = 'publish'", 'post_type = ?'];
    $params = [$args['post_type'] ?? 'post'];

    if (isset($args['s'])) {
        $where[] = "post_title LIKE ? ESCAPE '\\'";
        $params[] = '%' . addcslashes((string) $args['s'], '%_\\') . '%';
    }
    if (isset($args['author'])) {
        $where[] = 'post_author = ?';
        $params[] = (int) $args['author'];
    }

    $columns = ['date' => 'post_date', 'title' => 'post_title'];
    $column = $columns[$args['orderby'] ?? 'date'] ?? 'post_date';
    $direction = strtoupper((string) ($args['order'] ?? 'DESC')) === 'ASC' ? 'ASC' : 'DESC';
    $limit = max(1, (int) ($args['posts_per_page'] ?? 10));

    $sql = 'SELECT post_title FROM posts WHERE ' . implode(' AND ', $where)
        . " ORDER BY $column $direction LIMIT $limit";

    return [$sql, $params];
}

Values from the user (post_type, the search text, the author) are bound with ?. Names that cannot be bound (the order column and direction) are looked up in a whitelist, so the injection attempt in the last test falls back to post_date. The limit is cast to an integer and clamped to at least 1. The search text escapes % and _, so 100% is matched literally. Real WP_Query builds its SQL with $wpdb->prepare() in a similar spirit; see $wpdb and Custom Tables.

Post types and shortcodes

These practice custom post types and shortcodes.

4. Validate register_post_type() input (Intermediate)

A post type key must be 1 to 20 characters of lowercase letters, digits, underscores and dashes, and must not be one of WordPress's reserved names. The supports list may only contain known features. Write validate_post_type( $key, $args ) returning a list of error messages, empty when everything is fine.

PHP Exercise 4: validate_post_type

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.

Show solution
PHP
function validate_post_type(string $key, array $args = []): array
{
    $errors = [];
    if ($key === '' || strlen($key) > 20) {
        $errors[] = 'key must be 1-20 characters';
    }
    if (!preg_match('/^[a-z0-9_-]*$/', $key)) {
        $errors[] = 'key may only contain a-z, 0-9, _ and -';
    }
    if (in_array($key, RESERVED, true)) {
        $errors[] = 'key is reserved';
    }
    foreach ($args['supports'] ?? [] as $feature) {
        if (!in_array($feature, SUPPORTS, true)) {
            $errors[] = "unknown support: $feature";
        }
    }
    return $errors;
}

Collecting every problem instead of stopping at the first one gives the developer a complete report. Real WordPress returns a WP_Error for an invalid key, and its reserved list is longer than ours. The 20-character limit exists because the key is stored in a database column of that width.

5. A shortcode parser (Intermediate)

Write do_shortcode( $text, $tags ). $tags maps a shortcode name to a callback receiving ( array $atts, ?string $content ). Support self-closing [name a="1" b='2'] and enclosing [name]content[/name]. Unknown shortcodes stay in the text exactly as written.

PHP Exercise 5: do_shortcode

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.

Show solution
PHP
function do_shortcode(string $text, array $tags): string
{
    $names = implode('|', array_map('preg_quote', array_keys($tags)));
    $pattern = '/\[(' . $names . ')((?:\s+[^\]]*)?)\](?:(.*?)\[\/\1\])?/s';

    return preg_replace_callback($pattern, function (array $m) use ($tags): string {
        return $tags[$m[1]](parse_atts($m[2]), $m[3] ?? null);
    }, $text);
}

The pattern lists only registered names, so unknown shortcodes never match and stay in the text. The optional group (?:(.*?)\[\/\1\])? matches a closing tag only if one follows, which is how one pattern handles both forms. Real WordPress builds a similar regular expression from the registered tags, supports nested shortcodes and the [[escaped]] syntax, and runs the callback output through its own pipeline. See Shortcodes.

Security

These practice nonces, sanitizing, escaping and capabilities.

6. Nonces with time ticks (Advanced)

A WordPress nonce is a short token tied to an action, a user and a tick, a 12-hour time window. Write create_nonce( $action, $userId, $now ) and verify_nonce( $nonce, $action, $userId, $now ). Hash tick|action|userId with HMAC-SHA256 and a secret, and keep the first 10 characters. Verification returns 1 if the nonce was made in the current tick, 2 if in the previous tick, and false otherwise. Compare with hash_equals().

PHP Exercise 6: create and verify a nonce

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.

Show solution
PHP
function create_nonce(string $action, int $userId, int $now): string
{
    $tick = nonce_tick($now);
    return substr(hash_hmac('sha256', "$tick|$action|$userId", SECRET), 0, 10);
}

function verify_nonce(string $nonce, string $action, int $userId, int $now): int|false
{
    $tick = nonce_tick($now);
    foreach ([1 => $tick, 2 => $tick - 1] as $result => $candidateTick) {
        $expected = substr(hash_hmac('sha256', "$candidateTick|$action|$userId", SECRET), 0, 10);
        if (hash_equals($expected, $nonce)) {
            return $result;
        }
    }
    return false;
}

Because the action and user ID are part of the hashed data, a nonce for one action or user cannot be reused for another. Because the tick is part of it too, a nonce expires after at most 24 hours (two ticks). Real WordPress uses the same shape of design, with wp_hash(), the session token and a 12-hour tick, but the exact hashed string differs. Remember that a nonce protects against CSRF only: it never replaces a capability check.

7. Sanitize on the way in, escape on the way out (Intermediate)

Write three small functions. sanitize_text( $s ) removes script and style blocks, strips remaining tags, collapses runs of whitespace into one space and trims. esc_html( $s ) makes text safe inside HTML, including quotes. absint( $v ) returns a non-negative integer.

PHP Exercise 7: sanitize and escape

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.

Show solution
PHP
function sanitize_text(string $s): string
{
    $s = preg_replace('@<(script|style)[^>]*?>.*?</\1>@si', '', $s);
    $s = strip_tags($s);
    return trim(preg_replace('/\s+/', ' ', $s));
}

function esc_html(string $s): string
{
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function absint(mixed $v): int
{
    return abs((int) $v);
}

The script block is removed before strip_tags(), because strip_tags() alone would keep the text alert(1). WordPress's sanitize_text_field() does more (it strips invalid UTF-8, line breaks and percent-encoded octets); ours shows the idea. Sanitizing cleans input when you receive it. Escaping prepares a value for one specific output context when you print it. They are two separate jobs: see Escaping Output.

8. Roles, capabilities and a meta capability (Intermediate)

Roles are lists of capabilities. Write user_can( $user, $cap, $postAuthorId ). For ordinary capabilities, check the user's role. For the meta capability edit_post, map it to a primitive capability first: the user needs edit_posts for their own post and edit_others_posts for someone else's. This is what WordPress's map_meta_cap() does for you.

PHP Exercise 8: user_can

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.

Show solution
PHP
function user_can(array $user, string $cap, ?int $postAuthorId = null): bool
{
    if ($cap === 'edit_post') {
        $cap = $postAuthorId === $user['id'] ? 'edit_posts' : 'edit_others_posts';
    }
    return in_array($cap, ROLES[$user['role']] ?? [], true);
}

Meta capabilities such as edit_post describe an action on one object, so they need context (the post). The mapping step turns them into primitive capabilities that roles actually hold. Always check the specific thing you are about to do, for example current_user_can( 'edit_post', $post_id ), not just a role name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 3, why is the sort column looked up in a whitelist instead of bound with a ? placeholder?

    Prepared statements bind values only. Identifiers and keywords such as the order column and ASC or DESC are part of the statement structure, so they must be chosen from a fixed list in your code.
  2. 2. What does have_posts() do in your own loop implementation?

    have_posts() is a pure check. the_post() is the function that moves the position and sets the global post, which is why the pair works inside a while loop.
  3. 3. A nonce was created 13 hours ago. With a 12-hour tick, what does verification return?

    Verification accepts the current tick (result 1) and the previous tick (result 2). A nonce therefore lives between 12 and 24 hours.
  4. 4. Why does a nonce check not replace a capability check?

    Nonces defend against cross-site request forgery. Whether this user may perform the action is a separate question that only current_user_can() answers.

Summary

  • Practice with stand-ins teaches the idea behind each WordPress function, even though real WordPress cannot run on this page.
  • Filters run in ascending priority order and pass the value along; the loop is a position in a shared query object.
  • Bind values in SQL and whitelist identifiers; cast numbers; escape LIKE wildcards.
  • Validate keys and arguments early and report every problem at once.
  • Nonces bind an action, a user and a time window, and are separate from capability checks.
  • Sanitize input once when it arrives; escape output for its context every time you print it.

Keep going with WordPress Interview Questions.