options = get_option( 'aio_options', [] );
$perf_active = aio_is_module_active( 'opt-module-performance' );
$seo_active = aio_is_module_active( 'opt-module-optimizer' );
add_filter( 'cron_schedules', [ $this, 'add_cron_intervals' ] );
/* ------------------------------------------------------------------
* A. Speed & Media Optimization (tied to Speed & Optimize module)
* ------------------------------------------------------------------ */
if ( $perf_active ) {
if ( ! empty( $this->options['opt-perf-webp'] ) ) {
add_filter( 'wp_generate_attachment_metadata', [ $this, 'schedule_webp_conversion' ], 10, 2 );
add_action( 'aio_convert_webp_cron', [ $this, 'process_webp_conversion' ] );
}
add_action( 'aio_process_webp_bulk_queue', [ $this, 'process_webp_bulk_queue' ] );
if ( ! empty( $this->options['opt-perf-lazyload'] ) && ! aio_is_speed_safe_mode() ) {
add_filter( 'wp_lazy_loading_enabled', '__return_true' );
}
// Note: Smart LazyLoad, Smart LCP, Auto Image Dimensions, Font Swap, YouTube Facade,
// Delay JS, and Safe HTML Minify are executed in a single unified pass by AIO_Speed_HTML
// inside modules/performance/class-aio-speed-html.php.
if ( ! empty( $this->options['optEnableMediaReplace'] ) ) {
add_filter( 'attachment_fields_to_edit', [ $this, 'add_media_replace_field' ], 10, 2 );
add_action( 'edit_attachment', [ $this, 'process_media_replace' ] );
}
require_once dirname( __FILE__ ) . '/class-aio-caching.php';
new AIO_Caching();
}
/* ------------------------------------------------------------------
* B. On-Page & Technical SEO (deferred to init priority 5 so Yoast,
* RankMath, AIOSEO & SEOPress are already loaded before checking)
* ------------------------------------------------------------------ */
if ( $seo_active ) {
if ( ! empty( $this->options['optEnableAutoAltTags'] ) ) {
add_filter( 'wp_get_attachment_image_attributes', [ $this, 'auto_fill_alt_tags' ], 10, 3 );
}
add_action( 'init', [ $this, 'register_seo_hooks' ], 5 );
}
}
/**
* Detect active 3rd-party SEO suites AFTER all plugins have loaded.
*/
public function is_third_party_seo_active() {
return defined( 'WPSEO_VERSION' )
|| defined( 'RANK_MATH_VERSION' )
|| defined( 'AIOSEO_VERSION' )
|| defined( 'SEOPRESS_VERSION' )
|| class_exists( 'All_in_One_SEO_Pack' );
}
/**
* Register SEO meta, OpenGraph, Sitemap, Schema, and Per-Post Meta Box hooks safely on init.
*/
public function register_seo_hooks() {
if ( $this->is_third_party_seo_active() ) {
return;
}
// Per-post/page/product SEO Meta Box (enabled by default unless explicitly turned off)
$metabox_enabled = ! isset( $this->options['optEnableSeoMetaBox'] ) || ! empty( $this->options['optEnableSeoMetaBox'] );
if ( $metabox_enabled ) {
if ( is_admin() ) {
add_action( 'add_meta_boxes', [ $this, 'register_seo_meta_box' ] );
add_action( 'save_post', [ $this, 'save_seo_meta_box' ], 10, 2 );
}
add_filter( 'pre_get_document_title', [ $this, 'filter_custom_document_title' ], 20 );
add_filter( 'wp_robots', [ $this, 'filter_custom_robots' ], 20 );
}
if ( ! empty( $this->options['optEnableMetaTags'] ) || $metabox_enabled ) {
add_action( 'wp_head', [ $this, 'generate_meta_tags' ], 1 );
}
if ( ! empty( $this->options['optEnableOpenGraph'] ) ) {
add_filter( 'language_attributes', [ $this, 'add_og_xml_ns' ] );
add_action( 'wp_head', [ $this, 'generate_open_graph' ], 2 );
}
if ( ! empty( $this->options['optEnableSitemap'] ) ) {
$this->register_sitemap_rewrite();
add_filter( 'query_vars', [ $this, 'register_sitemap_query_var' ] );
add_action( 'template_redirect', [ $this, 'render_sitemap' ], 1 );
add_action( 'save_post', [ $this, 'purge_sitemap_cache' ] );
add_action( 'deleted_post', [ $this, 'purge_sitemap_cache' ] );
add_action( 'aio_tools_settings_updated', [ $this, 'purge_sitemap_cache' ] );
}
if ( ! empty( $this->options['optEnableSchema'] ) ) {
add_action( 'wp_head', [ $this, 'generate_schema_markup' ], 2 );
}
}
public function register_seo_meta_box() {
$screens = [ 'post', 'page' ];
if ( post_type_exists( 'product' ) ) {
$screens[] = 'product';
}
foreach ( $screens as $screen ) {
add_meta_box(
'aio_seo_meta_box',
__( 'AIO Tools — SEO & Social Meta', 'aio-tools' ),
[ $this, 'render_seo_meta_box' ],
$screen,
'normal',
'high'
);
}
}
public function render_seo_meta_box( $post ) {
wp_nonce_field( 'aio_save_seo_metabox', 'aio_seo_metabox_nonce' );
$seo_title = (string) get_post_meta( $post->ID, '_aio_seo_title', true );
$seo_desc = (string) get_post_meta( $post->ID, '_aio_seo_desc', true );
$seo_og_img = (string) get_post_meta( $post->ID, '_aio_seo_og_image', true );
$seo_noindex = (string) get_post_meta( $post->ID, '_aio_seo_noindex', true );
?>
purge_sitemap_cache();
}
public function filter_custom_document_title( $title ) {
if ( is_singular() ) {
$post_id = get_queried_object_id();
if ( $post_id ) {
$custom = trim( (string) get_post_meta( $post_id, '_aio_seo_title', true ) );
if ( '' !== $custom ) {
return $custom;
}
}
}
return $title;
}
public function filter_custom_robots( $robots ) {
if ( is_singular() ) {
$post_id = get_queried_object_id();
if ( $post_id && '1' === (string) get_post_meta( $post_id, '_aio_seo_noindex', true ) ) {
$robots['noindex'] = true;
}
}
return $robots;
}
public function purge_sitemap_cache() {
delete_transient( 'aio_sitemap_xml_cache' );
}
public function schedule_webp_conversion( $meta, $attachment_id ) {
if ( ! wp_next_scheduled( 'aio_convert_webp_cron', [ $attachment_id ] ) ) {
wp_schedule_single_event( time() + 5, 'aio_convert_webp_cron', [ $attachment_id ] );
}
return $meta;
}
public function add_cron_intervals( $schedules ) {
$schedules['aio_every_minute'] = [
'interval' => 60,
'display' => __( 'Every Minute', 'aio-tools' ),
];
return $schedules;
}
public function process_webp_conversion( $attachment_id ) {
$delete_original = ! empty( $this->options['opt-perf-webp-delete-original'] );
aio_generate_webp_for_attachment( $attachment_id, $delete_original );
}
public function process_webp_bulk_queue() {
$stats = get_option( 'aio_webp_bulk_stats' );
if ( ! $stats || empty( $stats['is_running'] ) || empty( $stats['queue'] ) ) {
wp_clear_scheduled_hook( 'aio_process_webp_bulk_queue' );
return;
}
$batch = array_splice( $stats['queue'], 0, 10 );
$delete_original = ! empty( $this->options['opt-perf-webp-delete-original'] );
foreach ( $batch as $id ) {
$result = aio_generate_webp_for_attachment( $id, $delete_original );
$stats['processed']++;
if ( is_array( $result ) && ! empty( $result['success'] ) ) {
$stats['original_bytes'] += $result['original_size'];
$stats['webp_bytes'] += $result['webp_size'];
update_post_meta( $id, '_aio_webp_converted', true );
} else {
update_post_meta( $id, '_aio_webp_converted', 'failed_or_skipped' );
}
}
if ( empty( $stats['queue'] ) ) {
$stats['is_running'] = false;
wp_clear_scheduled_hook( 'aio_process_webp_bulk_queue' );
}
update_option( 'aio_webp_bulk_stats', $stats, false );
}
/**
* Safe HTML Minifier fallback helper.
*/
public function minify_html_output( $buffer ) {
if ( empty( $buffer ) || stripos( $buffer, ']*>.*?\1>#is',
function ( $matches ) use ( &$placeholders, &$index ) {
$token = '%%AIO_MINIFY_BLOCK_' . ( $index++ ) . '%%';
$placeholders[ $token ] = $matches[0];
return $token;
},
$buffer
);
if ( null === $protected ) {
return $buffer;
}
$minified = preg_replace( '/).)*-->/s', '', $protected );
if ( null !== $minified ) {
$minified = preg_replace( [ '/>[^\S ]+/s', '/[^\S ]+', '<', '$1' ], $minified );
}
if ( null === $minified ) {
return $buffer;
}
if ( ! empty( $placeholders ) ) {
$minified = strtr( $minified, $placeholders );
}
return $minified;
}
public function auto_fill_alt_tags( $attr, $attachment, $size ) {
if ( empty( $attr['alt'] ) ) {
$attr['alt'] = trim( wp_strip_all_tags( get_the_title( $attachment->ID ) ) );
if ( empty( $attr['alt'] ) ) {
$parent_id = wp_get_post_parent_id( $attachment->ID );
if ( $parent_id ) {
$attr['alt'] = trim( wp_strip_all_tags( get_the_title( $parent_id ) ) );
}
}
}
return $attr;
}
public function add_media_replace_field( $form_fields, $post ) {
if ( function_exists( 'get_current_screen' ) ) {
$screen = get_current_screen();
if ( $screen && 'attachment' === $screen->id ) {
$html = '';
$html .= '' . esc_html__( 'Upload a new file to replace the current one. Note: The old file will be deleted permanently.', 'aio-tools' ) . '
';
$html .= wp_nonce_field( 'aio_media_replace_action', 'aio_media_replace_nonce', true, false );
$form_fields['aio_media_replace'] = [
'label' => __( 'Replace File', 'aio-tools' ),
'input' => 'html',
'html' => $html,
];
}
}
return $form_fields;
}
public function process_media_replace( $attachment_id ) {
if ( ! current_user_can( 'edit_post', $attachment_id ) || ! current_user_can( 'upload_files' ) ) {
return;
}
if ( ! empty( $_FILES['aio_media_replace']['name'] ) ) {
if ( ! isset( $_POST['aio_media_replace_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['aio_media_replace_nonce'] ) ), 'aio_media_replace_action' ) ) {
return;
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$uploaded_file = $_FILES['aio_media_replace']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$upload_overrides = [ 'test_form' => false ];
$old_file = get_attached_file( $attachment_id );
$movefile = wp_handle_upload( $uploaded_file, $upload_overrides );
if ( $movefile && ! isset( $movefile['error'] ) ) {
if ( $old_file && file_exists( $old_file ) ) {
wp_delete_file( $old_file );
}
$new_file = $movefile['file'];
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->update(
$wpdb->posts,
[ 'post_mime_type' => $movefile['type'], 'guid' => $movefile['url'] ],
[ 'ID' => $attachment_id ]
);
update_attached_file( $attachment_id, $new_file );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $new_file );
wp_update_attachment_metadata( $attachment_id, $attach_data );
}
}
}
public function generate_meta_tags() {
if ( is_singular() ) {
global $post;
if ( ! $post ) {
return;
}
$custom_desc = trim( (string) get_post_meta( $post->ID, '_aio_seo_desc', true ) );
if ( '' !== $custom_desc ) {
echo '' . "\n";
return;
}
if ( empty( $this->options['optEnableMetaTags'] ) ) {
return;
}
$raw = ! empty( $post->post_excerpt ) ? $post->post_excerpt : $post->post_content;
$desc = wp_trim_words( wp_strip_all_tags( strip_shortcodes( (string) $raw ) ), 30, '...' );
if ( ! empty( $desc ) ) {
echo '' . "\n";
}
} elseif ( ( is_front_page() || is_home() ) && ! empty( $this->options['optEnableMetaTags'] ) ) {
$desc = get_bloginfo( 'description' );
if ( ! empty( $desc ) ) {
echo '' . "\n";
}
}
}
public function add_og_xml_ns( $output ) {
if ( strpos( $output, 'og: http://ogp.me/ns#' ) === false ) {
return $output . ' prefix="og: http://ogp.me/ns#"';
}
return $output;
}
public function generate_open_graph() {
if ( is_singular() ) {
global $post;
$custom_title = $post ? trim( (string) get_post_meta( $post->ID, '_aio_seo_title', true ) ) : '';
$custom_desc = $post ? trim( (string) get_post_meta( $post->ID, '_aio_seo_desc', true ) ) : '';
$custom_img = $post ? trim( (string) get_post_meta( $post->ID, '_aio_seo_og_image', true ) ) : '';
$title = '' !== $custom_title ? $custom_title : get_the_title();
$url = get_permalink();
if ( '' !== $custom_desc ) {
$desc = $custom_desc;
} else {
$raw = ( $post && ! empty( $post->post_excerpt ) ) ? $post->post_excerpt : ( $post ? $post->post_content : '' );
$desc = wp_trim_words( wp_strip_all_tags( strip_shortcodes( (string) $raw ) ), 30, '...' );
}
$type = is_singular( 'product' ) ? 'product' : 'article';
$image = '' !== $custom_img ? $custom_img : ( $post ? get_the_post_thumbnail_url( $post->ID, 'large' ) : '' );
} else {
$title = get_bloginfo( 'name' );
$url = home_url( '/' );
$desc = get_bloginfo( 'description' );
$type = 'website';
$image = has_custom_logo() ? wp_get_attachment_image_url( get_theme_mod( 'custom_logo' ), 'full' ) : '';
}
echo '' . "\n";
echo '' . "\n";
echo '' . "\n";
echo '' . "\n";
if ( ! empty( $desc ) ) {
echo '' . "\n";
}
if ( ! empty( $image ) ) {
echo '' . "\n";
}
echo '' . "\n";
}
public function register_sitemap_rewrite() {
add_rewrite_rule( '^sitemap\.xml$', 'index.php?aio_sitemap=1', 'top' );
}
public function register_sitemap_query_var( $vars ) {
$vars[] = 'aio_sitemap';
return $vars;
}
public function render_sitemap() {
$uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
$path = trim( (string) wp_parse_url( $uri, PHP_URL_PATH ), '/' );
$home_path = trim( (string) wp_parse_url( home_url(), PHP_URL_PATH ), '/' );
if ( '' !== $home_path && ( $path === $home_path || strpos( $path, $home_path . '/' ) === 0 ) ) {
$path = trim( substr( $path, strlen( $home_path ) ), '/' );
}
if ( get_query_var( 'aio_sitemap' ) || 'sitemap.xml' === $path ) {
$xml = get_transient( 'aio_sitemap_xml_cache' );
if ( false === $xml ) {
ob_start();
echo '' . "\n";
echo '' . "\n";
echo '' . esc_url( home_url( '/' ) ) . 'daily1.0' . "\n";
$post_types = [ 'post', 'page' ];
if ( post_type_exists( 'product' ) ) {
$post_types[] = 'product';
}
$query = new WP_Query( [
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => 1000,
'orderby' => 'modified',
'order' => 'DESC',
'no_found_rows' => true,
'update_post_meta_cache' => true,
'update_post_term_cache' => false,
] );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
if ( '1' === (string) get_post_meta( get_the_ID(), '_aio_seo_noindex', true ) ) {
continue;
}
$modified = get_the_modified_time( 'c' );
echo '' . esc_url( get_permalink() ) . '' . esc_html( $modified ) . '0.8' . "\n";
}
wp_reset_postdata();
}
echo '';
$xml = ob_get_clean();
set_transient( 'aio_sitemap_xml_cache', $xml, 12 * HOUR_IN_SECONDS );
}
status_header( 200 );
header( 'Content-Type: application/xml; charset=utf-8' );
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo $xml;
exit;
}
}
public function generate_schema_markup() {
$graphs = [];
if ( is_front_page() || is_home() ) {
$graphs[] = [
'@type' => 'WebSite',
'name' => get_bloginfo( 'name' ),
'url' => home_url( '/' ),
];
} elseif ( is_singular() ) {
global $post;
if ( ! $post ) {
return;
}
// BreadcrumbList Schema
$items = [];
$items[] = [
'@type' => 'ListItem',
'position' => 1,
'name' => __( 'Home', 'aio-tools' ),
'item' => home_url( '/' ),
];
$pos = 2;
if ( is_singular( 'post' ) ) {
$cats = get_the_category( $post->ID );
if ( ! empty( $cats ) ) {
$items[] = [
'@type' => 'ListItem',
'position' => $pos++,
'name' => $cats[0]->name,
'item' => get_category_link( $cats[0]->term_id ),
];
}
} elseif ( is_singular( 'product' ) && function_exists( 'wc_get_page_permalink' ) ) {
$shop_url = wc_get_page_permalink( 'shop' );
if ( $shop_url ) {
$items[] = [
'@type' => 'ListItem',
'position' => $pos++,
'name' => __( 'Shop', 'aio-tools' ),
'item' => $shop_url,
];
}
}
$items[] = [
'@type' => 'ListItem',
'position' => $pos,
'name' => get_the_title( $post ),
'item' => get_permalink( $post ),
];
$graphs[] = [
'@type' => 'BreadcrumbList',
'itemListElement' => $items,
];
if ( is_singular( 'post' ) ) {
$article = [
'@type' => 'Article',
'headline' => get_the_title( $post ),
'datePublished' => get_the_date( 'c', $post ),
'dateModified' => get_the_modified_date( 'c', $post ),
'author' => [
'@type' => 'Person',
'name' => get_the_author_meta( 'display_name', $post->post_author ),
],
'publisher' => [
'@type' => 'Organization',
'name' => get_bloginfo( 'name' ),
],
];
if ( has_post_thumbnail( $post ) ) {
$article['image'] = get_the_post_thumbnail_url( $post->ID, 'full' );
}
$graphs[] = $article;
} elseif ( is_singular( 'product' ) && function_exists( 'wc_get_product' ) && ( ! function_exists( 'WC' ) || empty( WC()->structured_data ) ) ) {
$product = wc_get_product( $post->ID );
if ( $product ) {
$prod_schema = [
'@type' => 'Product',
'name' => $product->get_name(),
'description' => wp_trim_words( wp_strip_all_tags( $product->get_short_description() ?: $product->get_description() ), 40, '...' ),
'sku' => $product->get_sku(),
'offers' => [
'@type' => 'Offer',
'priceCurrency' => function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD',
'price' => $product->get_price(),
'availability' => $product->is_in_stock() ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
'url' => get_permalink( $post ),
],
];
if ( has_post_thumbnail( $post ) ) {
$prod_schema['image'] = get_the_post_thumbnail_url( $post->ID, 'full' );
}
$graphs[] = $prod_schema;
}
}
}
if ( ! empty( $graphs ) ) {
$payload = [
'@context' => 'https://schema.org',
'@graph' => $graphs,
];
echo '' . "\n";
}
}
}
new AIO_Optimizer();
if ( ! function_exists( 'aio_convert_single_file_to_webp' ) ) {
function aio_convert_single_file_to_webp( $src_path, $webp_path, $mime_type ) {
if ( ! file_exists( $src_path ) ) {
return false;
}
$success = false;
if ( function_exists( 'imagewebp' ) ) {
$image = null;
if ( 'image/jpeg' === $mime_type && function_exists( 'imagecreatefromjpeg' ) ) {
$image = @imagecreatefromjpeg( $src_path );
} elseif ( 'image/png' === $mime_type && function_exists( 'imagecreatefrompng' ) ) {
$image = @imagecreatefrompng( $src_path );
}
if ( $image ) {
if ( function_exists( 'imagepalettetotruecolor' ) ) {
@imagepalettetotruecolor( $image );
}
if ( 'image/png' === $mime_type ) {
@imagealphablending( $image, false );
@imagesavealpha( $image, true );
}
$success = @imagewebp( $image, $webp_path, 85 );
@imagedestroy( $image );
}
}
if ( ! $success || ! file_exists( $webp_path ) || filesize( $webp_path ) < 100 ) {
$editor = wp_get_image_editor( $src_path );
if ( ! is_wp_error( $editor ) ) {
$editor->set_quality( 85 );
$saved = $editor->save( $webp_path, 'image/webp' );
$success = ! is_wp_error( $saved );
}
}
return $success && file_exists( $webp_path ) && filesize( $webp_path ) > 100;
}
}
if ( ! function_exists( 'aio_generate_webp_for_attachment' ) ) {
function aio_generate_webp_for_attachment( $attachment_id, $delete_original = false ) {
$file_path = get_attached_file( $attachment_id );
if ( ! $file_path || ! file_exists( $file_path ) ) {
return false;
}
$filetype = wp_check_filetype( $file_path );
$mime_type = ! empty( $filetype['type'] ) ? $filetype['type'] : ( function_exists( 'mime_content_type' ) ? mime_content_type( $file_path ) : '' );
if ( ! in_array( $mime_type, [ 'image/jpeg', 'image/png' ], true ) ) {
return false;
}
$path_info = pathinfo( $file_path );
$base_dir = $path_info['dirname'];
$webp_filename = $path_info['filename'] . '.webp';
$webp_path = $base_dir . '/' . $webp_filename;
// Prevent filename collision when both banner.jpg and banner.png exist in the same folder
$use_basename_suffix = false;
if ( file_exists( $webp_path ) && $webp_path !== $file_path ) {
$use_basename_suffix = true;
$webp_filename = $path_info['basename'] . '.webp';
$webp_path = $base_dir . '/' . $webp_filename;
}
if ( ! aio_convert_single_file_to_webp( $file_path, $webp_path, $mime_type ) ) {
return [ 'success' => false ];
}
$total_orig_bytes = (int) filesize( $file_path );
$total_webp_bytes = (int) filesize( $webp_path );
// Also convert all generated WordPress & WooCommerce intermediate image sizes
$metadata = wp_get_attachment_metadata( $attachment_id );
$converted_files = [];
if ( is_array( $metadata ) ) {
if ( ! empty( $metadata['file'] ) ) {
$meta_dir = pathinfo( $metadata['file'], PATHINFO_DIRNAME );
$metadata['file'] = ( $meta_dir && '.' !== $meta_dir ? $meta_dir . '/' : '' ) . $webp_filename;
}
if ( ! empty( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
foreach ( $metadata['sizes'] as $size_key => $size_info ) {
if ( empty( $size_info['file'] ) ) {
continue;
}
$sub_src = $base_dir . '/' . $size_info['file'];
$sub_info = pathinfo( $sub_src );
$sub_name = $use_basename_suffix ? ( $sub_info['basename'] . '.webp' ) : ( $sub_info['filename'] . '.webp' );
$sub_webp = $base_dir . '/' . $sub_name;
if ( ! $use_basename_suffix && file_exists( $sub_webp ) && $sub_webp !== $sub_src ) {
$sub_webp = $base_dir . '/' . $sub_info['basename'] . '.webp';
}
if ( isset( $converted_files[ $sub_src ] ) ) {
$metadata['sizes'][ $size_key ]['file'] = basename( $converted_files[ $sub_src ] );
$metadata['sizes'][ $size_key ]['mime-type'] = 'image/webp';
continue;
}
if ( file_exists( $sub_src ) && aio_convert_single_file_to_webp( $sub_src, $sub_webp, $mime_type ) ) {
$total_orig_bytes += (int) filesize( $sub_src );
$total_webp_bytes += (int) filesize( $sub_webp );
$converted_files[ $sub_src ] = $sub_webp;
$metadata['sizes'][ $size_key ]['file'] = basename( $sub_webp );
$metadata['sizes'][ $size_key ]['mime-type'] = 'image/webp';
}
}
}
wp_update_attachment_metadata( $attachment_id, $metadata );
}
update_attached_file( $attachment_id, $webp_path );
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->update(
$wpdb->posts,
[ 'post_mime_type' => 'image/webp' ],
[ 'ID' => $attachment_id ],
[ '%s' ],
[ '%d' ]
);
if ( $delete_original ) {
foreach ( array_keys( $converted_files ) as $old_thumb ) {
if ( $old_thumb !== $webp_path && file_exists( $old_thumb ) ) {
wp_delete_file( $old_thumb );
}
}
if ( $file_path !== $webp_path && file_exists( $file_path ) ) {
wp_delete_file( $file_path );
}
}
return [
'success' => true,
'original_size' => $total_orig_bytes,
'webp_size' => $total_webp_bytes,
];
}
}