Okay so I sorta have a solution. It’s not perfect, it creates some bugs (some images come back to me as 404), but it does the job. Most of my image are appearing as expected!
Here is my code. It automatically execute itself after a page reload following the code implementation.
<?php
function point_image_url_to_main_domain() {
$images = array();
$old_url = get_home_url();
$new_url = "https://barbandcarole.ca";
global $wpdb;
$optimole_img_ids = $wpdb->get_col("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'optimole_offload' AND meta_value = 'true'");
foreach ($optimole_img_ids as $img_id) {
$img_metadata = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND post_id = $img_id");
if(str_contains($img_metadata, $old_url)) {
$img_metadata = str_replace($old_url, $new_url, $img_metadata); //transforms the Optimole URL
$query = $wpdb->update(
$wpdb->postmeta,
['meta_value' => $img_metadata],
['post_id' => $img_id, 'meta_key' => '_wp_attachment_metadata']
); //use $wpdb->prepare if you make this into a user input.
//$query = 1;
if($query === false) {
echo "<p>The query failed!</p>";
} elseif ($query === 0) {
echo "<p>The query succeeded but no rows were updated.</p>";
} elseif ($query > 0) {
echo "<p>Query successful! Image ".$img_id."'s metadata was updated.</p>";
}
}
}
}
add_action("wp_after_admin_bar_render", "point_image_url_to_main_domain");
?>
I get a few error 404 from the server trying to look for images in localhost
still rather than through the barbandcarole.ca
Optimole url (probably caused by WHERE meta_key = 'optimole_offload' AND meta_value = 'true'"
), plus one 400 error over which my script was unable to go over (it was a CSS background image).
Those 4XX error triggers an error from the Optimole plugin:
Warning: Trying to access array offset on value of type bool in C:\xampp\htdocs\dev\barbandcarole\wp-content\plugins\optimole-wp\inc\tag_replacer.php on line 428
but I don’t sweat it too much and will try to fix the remaining error tomorrow by amelioration my code.
In my honest opinion, this kind of URL repointing should be a feature that comes with Optimole. It is really crucial for us advanced users who needs to make image-related adjustments (mostly in HTML/CSS) in test (hear: staging) environments.
-
This reply was modified 3 years, 7 months ago by Nazrinn.
-
This reply was modified 3 years, 7 months ago by Nazrinn.
-
This reply was modified 3 years, 7 months ago by Nazrinn.
-
This reply was modified 3 years, 7 months ago by Nazrinn.