Find Insecure http:// Links in Content (WP-CLI)
Adds a "wp find-http-links" command that lists posts containing http:// images, scripts or links, marking which point to your own domain, to clean up mixed content after moving to HTTPS.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'find-http-links', function ( $args, $assoc_args ) {
global $wpdb;
$host = (string) wp_parse_url( home_url(), PHP_URL_HOST );
$bare = preg_replace( '/^www\./', '', $host );
$items = array();
$rows = $wpdb->get_results(
"SELECT ID, post_type, post_title, post_content FROM {$wpdb->posts}
WHERE post_status IN ('publish','draft','future','private','pending') AND post_type NOT IN ('revision','nav_menu_item')
AND ( post_content LIKE '%src=\"http://%' OR post_content LIKE '%href=\"http://%' OR post_content LIKE '%src=''http://%' OR post_content LIKE '%href=''http://%' )"
);
foreach ( $rows as $row ) {
if ( ! preg_match_all( '/(?:src|href)=["\']http:\/\/([^\/"\']+)/i', $row->post_content, $matches ) ) {
continue;
}
$own = 0;
$other = 0;
foreach ( $matches[1] as $domain ) {
if ( preg_replace( '/^www\./', '', strtolower( $domain ) ) === strtolower( $bare ) ) {
$own++;
} else {
$other++;
}
}
if ( ! empty( $assoc_args['own'] ) && ! $own ) {
continue;
}
$items[] = array( 'ID' => $row->ID, 'type' => $row->post_type, 'own_domain' => $own, 'other_domains' => $other, 'title' => $row->post_title );
}
if ( ! $items ) {
WP_CLI::success( 'No http:// links found.' );
return;
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $items, array( 'ID', 'type', 'own_domain', 'other_domains', 'title' ) );
}, array(
'shortdesc' => 'Lists content with http:// links and images.',
'synopsis' => array(
array( 'type' => 'flag', 'name' => 'own', 'optional' => true, 'description' => 'Only links to this site.' ),
array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json', 'count' ) ),
),
) );
Notes
Add --own to list only links to your own domain, which can usually be switched to https:// safely.
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.