I wrote this plugin code to accomplish the task of saving the order to a “pages_order” hidden plaintext field:
function enqueue_my_scripts()
{
wp_register_script('PodsHelper', plugin_dir_url(__FILE__) . 'pods-helper.js', array(), filemtime(plugin_dir_path(__FILE__) . 'pods-helper.js'), true);
wp_enqueue_script('PodsHelper');
}
global $pagenow;
if (!empty($pagenow) && 'post.php' === $pagenow) {
add_action('admin_enqueue_scripts', __NAMESPACE__ . '\enqueue_my_scripts');
}
function initObserver() {
const observer = new MutationObserver(mutations => {
let files = document.querySelectorAll('.pods-dfv-list-item');
let order = [];
for (const file of files) {
let hiddenInput = file.querySelector('input[type="hidden"]');
if (!hiddenInput) {
order = [];
break;
} else {
order.push(hiddenInput.value);
}
}
let orderString = '[' + order.join(',') + ']';
let orderInput = document.querySelector('#pods-form-ui-pods-meta-pages-order');
orderInput.value = orderString;
});
observer.observe(document.querySelector('#pods-meta-more-fields'), {
childList: true,
subtree: true
});
}
if (document.readyState === 'complete') {
initObserver();
} else {
window.addEventListener('load', function () {
initObserver();
})
}
Pods should already save the order of the files as reordered when using a file field that allows for multiple files. Any other details about why this extra copy of the reordering is needed?
Hi Scott, please share the location where the file order is saved in the db.
For a post type with meta-based storage, the file details get stored in the postmeta:
* field_name
there are individual records for each attachment ID (wp_posts.ID) of the file uploaded/chosen
* _pods_field_name
there is one record for the full list of attachment IDs in the order they were saved, this is what is used for determining order when loading into the Pods form (which should also be used for normal every day output too)
Thanks! Here’s the code I used to retrieve the “pages” field:
$image_ids = get_post_meta($post_id, '_pods_pages', true);
$images = pods()->field('pages', array('orderby' => 'FIELD(ID, ' . implode(',', $image_ids) . ')'));
This should be default for field() so I’m going to look into why it’s not ordering that way for you.
Thanks, field() does work without the orderby, no worries, I was overthinking it.