Skip to content

Commit

Permalink
Cache expensive search query
Browse files Browse the repository at this point in the history
* For a day.
* Sort by file size.
  • Loading branch information
Inwerpsel committed Apr 27, 2022
1 parent 1b4af6b commit 80cdfb5
Showing 1 changed file with 38 additions and 11 deletions.
49 changes: 38 additions & 11 deletions functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,11 @@ function ( $urls, $post_id ) {
*/
function get_image_posts( $id ) {
global $wpdb;
$cache_key = "imgpost$id";
$cache = wp_cache_get( $cache_key );
if ( false !== $cache ) {
return $cache;
}

$att = get_post_custom( $id );
$file = $att['_wp_attached_file'][0];
Expand All @@ -415,7 +420,11 @@ function get_image_posts( $id ) {

$prepared_sql = $wpdb->prepare( $sql, $id, '%src="%' . $wpdb->esc_like( $file ) . '"%' );

return $wpdb->get_col( $prepared_sql );
$results = $wpdb->get_col( $prepared_sql );

wp_cache_add( $cache_key, $results, null, 3600 * 24 );

return $results;
}

/**
Expand Down Expand Up @@ -493,26 +502,44 @@ function () {
];

$results = new WP_Query( $args );

echo "<h1>PNG Report</h1>";
echo '<table>';
foreach ( $results->posts as $image_id ) {
echo '<tr>';
$images = array_map( function ( $image_id ) {
$src = wp_get_attachment_image_src( $image_id, 'full' )[0];
$title = get_the_title( $image_id );
$size_check = curl_get_file_size( $src );
$size = $size_check <= 0 ? '' : formatBytes( $size_check );
echo "<td><a href=\"$src\">#$image_id ($title)</a></td>";
echo "<td>size: $size</td>";

if ( empty( $_GET['detail'] ) ) {
continue;
return [
'id' => $image_id,
'src' => $src,
'title' => $title,
'size' => $size,
'size_bytes' =>$size_check,
];
}, $results->posts);

uasort( $images, function ( $a, $b ) {
if ( $a['size_bytes'] === $b['size_bytes'] ) {
return 0;
}

return $a['size_bytes'] > $b['size_bytes'] ? -1 : 1;
} );

echo "<h1>PNG Report</h1>";
echo '<table>';
foreach ( $images as $image ) {
$size = $image['size'];
$src = $image['size'];
$image_id = $image['id'];
$title = $image['title'];
echo '<tr>';
echo "<td>size: $size</td>";
echo "<td><a href=\"$src\">#$image_id ($title)</a></td>";

$image_posts = get_image_posts( $image_id );

echo '<td>';
echo '<ul>';
echo '<ul style="list-style-type: circle; padding-left: 100px">';
foreach ( $image_posts as $id ) {
$src = get_permalink( $id );
$edit_link = get_edit_post_link( $id );
Expand Down

0 comments on commit 80cdfb5

Please sign in to comment.