# Search Text Across All Content (WP-CLI)

> Adds a "wp search-content" command that finds an exact word or phrase in titles, content and excerpts of every post type, so you can locate old links, prices or names quickly.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: wp-cli, search, content
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cli-search-content/

## Code

```php
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
    return;
}

WP_CLI::add_command( 'search-content', function ( $args, $assoc_args ) {
    global $wpdb;

    $like    = '%' . $wpdb->esc_like( $args[0] ) . '%';
    $columns = array(
        'title'   => 'post_title',
        'content' => 'post_content',
        'excerpt' => 'post_excerpt',
    );
    $in      = isset( $assoc_args['in'], $columns[ $assoc_args['in'] ] ) ? array( $columns[ $assoc_args['in'] ] ) : array_values( $columns );
    $where   = implode( ' OR ', array_map( function ( $column ) {
        return "$column LIKE %s";
    }, $in ) );

    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT ID, post_type, post_status, post_title FROM {$wpdb->posts}
        WHERE post_type NOT IN ('revision','nav_menu_item','customize_changeset') AND post_status NOT IN ('trash','auto-draft')
        AND ( $where ) ORDER BY post_type, ID LIMIT 500",
        array_fill( 0, count( $in ), $like )
    ), ARRAY_A );

    if ( ! $rows ) {
        WP_CLI::success( 'No matches.' );
        return;
    }

    WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $rows, array( 'ID', 'post_type', 'post_status', 'post_title' ) );
}, array(
    'shortdesc' => 'Finds a word or phrase in post titles, content and excerpts.',
    'synopsis'  => array(
        array( 'type' => 'positional', 'name' => 'text', 'description' => 'Text to look for.' ),
        array( 'type' => 'assoc', 'name' => 'in', 'optional' => true, 'options' => array( 'title', 'content', 'excerpt' ) ),
        array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json', 'count', 'ids' ) ),
    ),
) );
```

## Notes

Matching is case-insensitive and literal; add --in=title to search titles only.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Search Text Across All Content (WP-CLI)" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
