@Shayne, first thing that is wrong about your code is that it is using single quotes (') instead of double quotes ("), which is said to be used:
Note the use of double quotes instead of single quotes. You must use double quotes when executing PHP functions from within WP All Import. You can’t use single quotes.
I asked Claude.ai to improve your code snippet from ChatGPT and it came with the following, which I managed to get working:
function update_wpbakery_image_ids($post_id, $xml_node, $is_update) {
// Get the post content
$content = get_post_field("post_content", $post_id);
// Skip if no content
if (empty($content)) {
return;
}
// Array of WP Bakery shortcodes that contain image IDs
$shortcode_patterns = array(
"vc_single_image" => "/\[vc_single_image[^\]]*image=\"(\d+)\"/",
"vc_gallery" => "/\[vc_gallery[^\]]*images=\"([^\"]+)\"/"
);
$modified = false;
foreach ($shortcode_patterns as $shortcode => $pattern) {
preg_match_all($pattern, $content, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $old_ids) {
// Handle both single IDs and comma-separated lists
$old_id_array = explode(",", $old_ids);
$new_id_array = array();
foreach ($old_id_array as $old_id) {
$old_id = trim($old_id);
// Get the attachment URL for the old ID
$old_attachment_url = wp_get_attachment_url($old_id);
if ($old_attachment_url) {
// Try to find the new attachment ID based on the same filename
$filename = basename($old_attachment_url);
$new_attachment = get_posts(array(
"post_type" => "attachment",
"post_status" => "inherit",
"fields" => "ids",
"meta_query" => array(
array(
"value" => $filename,
"compare" => "LIKE",
"key" => "_wp_attached_file"
)
)
));
if (!empty($new_attachment)) {
$new_id = $new_attachment[0];
$new_id_array[] = $new_id;
// Replace in content based on shortcode type
if ($shortcode === "vc_single_image") {
$content = preg_replace(
"/(\[vc_single_image[^\]]*image=\")" . $old_id . "\"/",
"$1" . $new_id . "\"",
$content
);
} elseif ($shortcode === "vc_gallery") {
$old_ids_pattern = preg_quote($old_ids, "/");
$new_ids = implode(",", $new_id_array);
$content = preg_replace(
"/(\[vc_gallery[^\]]*images=\")" . $old_ids_pattern . "\"/",
"$1" . $new_ids . "\"",
$content
);
}
$modified = true;
}
}
}
}
}
}
// Update post content if modifications were made
if ($modified) {
wp_update_post(array(
"ID" => $post_id,
"post_content" => $content
));
// Clear any caches
clean_post_cache($post_id);
}
}
I added this function to the Function Editor which is available from within the WP All Import Pro process.