Skip to content

Instantly share code, notes, and snippets.

@rayflores
Last active February 19, 2019 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayflores/33145280651272cb3b570d711e19d18f to your computer and use it in GitHub Desktop.
Save rayflores/33145280651272cb3b570d711e19d18f to your computer and use it in GitHub Desktop.
sort postmeta that is a serialized object by custom order of your choice - uksort function - custom index list order - always first
<?php
class Sort_The_List {
static public function get_postmeta_from_db( int $post_id ){
$full_meta = [];
$the_meta = get_post_meta( $post_id, '_your_meta_key', true );
foreach( $the_meta as $key => $value ){
if( is_array( $value ) || is_object( $value ) ) {
foreach( $value as $k => $v ) {
$full_meta[ $k ] = $v;
}
} else {
$full_specs[ $key ] = $value;
}
}
$full_meta = self::get_sorted_order($full_meta); // magic happens here ;)
return $full_meta;
}
/*
* uksort sort function - main function to call
* http://php.net/manual/en/function.uksort.php
*/
static public function get_sorted_order(&$arraytosort){
uksort($arraytosort,"self::get_sorted_order_cmp");
}
/*
* the custom compare callback function for uksort
*/
static public function get_sorted_order_cmp($a,$b){
/**
* Index of sorted 'key names' => 'values'
* Key name matches Items to sort Values
*/
$order = array(
'Always First' => 0,
'First Item' => 1,
'Second Item' => 2,
'Third Item' => 3,
'Fourth Item' => 4,
'Fifth Item' => 5,
'Sixth Item' => 6,
'Seventh Item' => 7,
'Eighth Item' => 8,
'Ninth Item' => 9,
'Tenth Item' => 10
);
return $order[$a] - $order[$b];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment