-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-find-images-command.php
100 lines (79 loc) · 2.54 KB
/
class-find-images-command.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
if ( ! class_exists( 'WP_CLI' ) ) {
return;
}
/**
* Find images in posts/pages/custom post types and generate CSV.
*
* @when after_wp_load
*/
class Find_Images_Command {
/**
* Find images in the database and generate CSV.
*
* ## OPTIONS
*
* <file>
* : Path to the text file containing image names.
*
* @param array $args Command arguments.
* @param array $assoc_args Command associative arguments.
*/
public function __invoke( $args, $assoc_args ) {
list( $file_path ) = $args;
if ( ! file_exists( $file_path ) ) {
WP_CLI::error( "File not found: $file_path" );
}
$image_names = file( $file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
$result = array();
foreach ( $image_names as $image_name ) {
$posts_with_image = $this->get_posts_with_image( $image_name );
foreach ( $posts_with_image as $post ) {
$result[] = array( 'image_name' => $image_name, 'post_url' => get_permalink( $post->ID ) );
}
}
if ( empty( $result ) ) {
WP_CLI::success( 'No matching images found in the database.' );
return;
}
$csv_file_path = dirname( $file_path ) . '/found_images.csv';
$file_handle = fopen( $csv_file_path, 'w' );
fputcsv( $file_handle, array( 'Image Name', 'Post URL' ) );
foreach ( $result as $row ) {
fputcsv( $file_handle, $row );
}
fclose( $file_handle );
$images_found_msg = WP_CLI::colorize("%B" . sprintf('Total images found: %d', count( $result ) ) . "%n");
WP_CLI::line($images_found_msg);
WP_CLI::success( "CSV file generated: $csv_file_path" );
}
/**
* Get posts containing the given image name.
*
* @param string $image_name Image name.
* @return array Array of posts.
*/
private function get_posts_with_image( $image_name ) {
global $wpdb;
$media_types = array( 'png', 'jpg', 'jpeg', 'svg', 'gif' );
// Remove the file extension from the image name
// as the final image name in the post content may have additional characters or numbers appended to it.
foreach ( $media_types as $type ) {
if ( preg_match( '/\.' . $type . '$/', $image_name ) ) {
$image_name = str_replace( '.' . $type, '', $image_name );
break;
}
}
WP_CLI::line( " - Searching for image: '$image_name'" );
$query = $wpdb->prepare(
"SELECT p.ID
FROM $wpdb->posts p
WHERE p.post_type IN ('page', 'post', 'product')
AND p.post_content LIKE %s",
'%' . $wpdb->esc_like( $image_name ) . '%'
);
$post_ids = $wpdb->get_col( $query );
return array_map( 'get_post', $post_ids );
}
}
WP_CLI::add_command( 'find-images', 'Find_Images_Command' );