Created
September 17, 2021 20:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The full explanation is here.