Skip to content

Instantly share code, notes, and snippets.

@bookchiq
Created September 17, 2021 20:28
Show Gist options
  • Save bookchiq/e6f7524efae71fa6a659b74abd03720c to your computer and use it in GitHub Desktop.
Save bookchiq/e6f7524efae71fa6a659b74abd03720c to your computer and use it in GitHub Desktop.
ACF/WordPress action to help with sorting serialized custom fields by meta_value
<?php
/**
* ACF's serialized data can't be used for sorting posts,
* so we're making a more useful copy for the purpose.
*
* @param int|string $post_id The ID of the post being edited.
* @return void
*/
function happyhumans_save_plaintext_metadata( $post_id ) {
// Get newly saved values.
$values = get_fields( $post_id );
// If this post has a "state" field, parse it down to plain-text and save it as a shadow record.
if ( ! empty( $values['state'] ) ) {
$plain_text_state = '';
foreach ( $values['state'] as $state ) {
$plain_text_state .= $state . ' ';
}
update_post_meta( $post_id, 'plain_text_state', trim( strtolower( $plain_text_state ) ) );
}
}
add_action( 'acf/save_post', 'happyhumans_save_plaintext_metadata' );
@bookchiq
Copy link
Author

The full explanation is here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment