Skip to content

Instantly share code, notes, and snippets.

@abidkakkur11
Created November 17, 2025 09:13
Show Gist options
  • Select an option

  • Save abidkakkur11/26780c6d7334e0f78cacac5d2d44f9d8 to your computer and use it in GitHub Desktop.

Select an option

Save abidkakkur11/26780c6d7334e0f78cacac5d2d44f9d8 to your computer and use it in GitHub Desktop.
Add A Media button near the ACF URL or any Field on Backend

Copy the filed ID by Right clicking on the field from the backend. Assign it into the field variable in the code(Line 13). Activate the snippet.

<?php
add_action('admin_enqueue_scripts', function($hook) {
// Load only on product edit pages
if ( ! in_array( $hook, ['post.php', 'post-new.php'], true ) ) return;
if ( get_post_type() !== 'product' ) return;
// Load WordPress media scripts
wp_enqueue_media();
// Inline script
$script = <<<JS
jQuery(document).ready(function($) {
var field = $('#acf-field_68b99c7c75166'); // your field ID
if (field.length) {
// Add "Add Media" button
var button = $('<button type="button" class="button add-media-btn" style="margin-top:5px;">Add Media</button>');
field.after(button);
// Add a preview link container
var preview = $('<a href="#" target="_blank" class="acf-media-preview" style="margin-left:10px;display:none;margin-top:5px;">View File</a>');
button.after(preview);
// If field already has value
if (field.val()) {
preview.attr('href', field.val()).show();
button.text('Change File');
}
button.on('click', function(e) {
e.preventDefault();
var frame = wp.media({
title: 'Select or Upload File',
button: { text: 'Use this file' },
multiple: false
});
frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
field.val(attachment.url).trigger('change');
// Update preview
preview.attr('href', attachment.url).show();
button.text('Change File');
});
frame.open();
});
}
});
JS;
wp_add_inline_script('jquery-core', $script);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment