Skip to content

Instantly share code, notes, and snippets.

@patrickfreitasdev
Created September 27, 2025 13:12
Show Gist options
  • Save patrickfreitasdev/6f7cb3cf52dc53919954a2af7c95bdc7 to your computer and use it in GitHub Desktop.
Save patrickfreitasdev/6f7cb3cf52dc53919954a2af7c95bdc7 to your computer and use it in GitHub Desktop.
<?php
// Update new posts to have the correct publication URL
add_filter('wp_insert_post_data', 'update_post_file_to_append_proxy', 10, 1);
function update_post_file_to_append_proxy(array $data): array
{
// We don't need to take actions for publications, any other post type we will proceeed.
if($data['post_type'] == 'publications'){
return $data;
}
// Extract the PDF URLs from the post content
$pdfs = extract_pdf_urls($data['post_content']);
if(empty($pdfs)){
return $data;
}
// Loop through the PDF URLs and update the post content with the correct publication URL
foreach ($pdfs as $pdf) {
$attachment_id = lookup_pdf_id_by_url($pdf);
if(!$attachment_id){
continue;
}
// Lookup the publication ID by the attachment ID
$publication_id = lookup_publication_id_by_attachment_id($attachment_id);
if(!$publication_id){
continue;
}
$new_url = "/download/publication/". $publication_id;
$data['post_content'] = str_replace($pdf, $new_url, $data['post_content']);
}
return $data;
}
function extract_pdf_urls(string $post_content): array {
$pdf_urls = [];
$pattern = '/https?:\/\/[^\s<>"\'()]+?\.pdf\b/i';
if (preg_match_all($pattern, $post_content, $matches)) {
$pdf_urls = array_unique($matches[0]); // Remove duplicates
}
return array_values($pdf_urls);
}
function lookup_publication_id_by_attachment_id(int $attachment_id): ?int {
$posts = get_posts([
'post_type' => 'publications',
'posts_per_page' => 1,
'meta_query' => [
[
'key' => 'pdf_file', // ACF field key
'value' => $attachment_id,
'type' => 'NUMERIC',
],
],
'fields' => 'ids',
]);
return !empty($posts) ? (int) $posts[0] : null;
}
function lookup_pdf_id_by_url(string $url): ?int {
$url = esc_url_raw($url);
$upload_dir = wp_upload_dir();
$file_path = str_replace($upload_dir['baseurl'], '', $url);
$file_path = trim($file_path, '/');
$posts = get_posts([
'post_type' => 'attachment',
'posts_per_page' => 1,
'meta_query' => [
[
'key' => '_wp_attached_file',
'value' => $file_path,
],
],
'fields' => 'ids',
]);
return !empty($posts) ? (int) $posts[0] : null;
}
// handle existing ones, it could be a fresh mu-plugin to run once only, use ?update-posts to trigger it
add_action('admin_init', 'handle_update_posts_request');
function handle_update_posts_request() {
if (!current_user_can('manage_options')) {
return;
}
if (isset($_GET['update-posts'])) {
// Show loading state and AJAX script
add_action('admin_notices', function() {
echo '<div id="pdf-update-notice" class="notice notice-info"><p><span class="spinner is-active" style="float: none; margin-right: 10px;"></span>Processing PDF URL updates... This may take a moment.</p></div>';
});
add_action('admin_footer', function() {
?>
<script>
jQuery(document).ready(function($) {
// Start the update process
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'update_pdf_urls_ajax',
nonce: '<?php echo wp_create_nonce('update_pdf_urls_nonce'); ?>'
},
success: function(response) {
if (response.success) {
$('#pdf-update-notice').removeClass('notice-info').addClass('notice-success').html('<p><strong>Complete!</strong> Updated ' + response.data.total_updated + ' posts with PDF URL replacements.</p>');
} else {
$('#pdf-update-notice').removeClass('notice-info').addClass('notice-error').html('<p><strong>Error:</strong> ' + response.data + '</p>');
}
},
error: function() {
$('#pdf-update-notice').removeClass('notice-info').addClass('notice-error').html('<p><strong>Error:</strong> Failed to process PDF URL updates.</p>');
}
});
});
</script>
<?php
});
}
}
// AJAX handler for PDF URL updates
add_action('wp_ajax_update_pdf_urls_ajax', 'handle_pdf_urls_ajax');
function handle_pdf_urls_ajax() {
// Verify nonce
if (!wp_verify_nonce($_POST['nonce'], 'update_pdf_urls_nonce')) {
wp_die('Security check failed');
}
if (!current_user_can('manage_options')) {
wp_die('Insufficient permissions');
}
// Process updates for each post type
$post_types = ['post', 'page', 'projects', 'research_theme'];
$total_updated = 0;
foreach ($post_types as $post_type) {
$posts = get_posts([
'post_type' => $post_type,
'posts_per_page' => -1,
]);
foreach ($posts as $post) {
$pdfs = extract_pdf_urls($post->post_content);
if (!empty($pdfs)) {
$updated_content = $post->post_content;
foreach ($pdfs as $pdf) {
$attachment_id = lookup_pdf_id_by_url($pdf);
if ($attachment_id) {
$publication_id = lookup_publication_id_by_attachment_id($attachment_id);
if ($publication_id) {
$new_url = "/download/publication/" . $publication_id;
$updated_content = str_replace($pdf, $new_url, $updated_content);
}
}
}
if ($updated_content !== $post->post_content) {
wp_update_post([
'ID' => $post->ID,
'post_content' => $updated_content,
]);
$total_updated++;
}
}
}
}
wp_send_json_success(['total_updated' => $total_updated]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment