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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.