Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.