acf_order_by_search()
No Hooks.
Returns
null. Nothing (null).
Usage
acf_order_by_search( $array, $search );
- $array(required)
- .
- $search(required)
- .
acf_order_by_search() acf order by search code ACF 6.8.8
function acf_order_by_search( $array, $search ) {
// vars
$weights = array();
$needle = strtolower( $search );
// add key prefix
foreach ( array_keys( $array ) as $k ) {
$array[ '_' . $k ] = acf_extract_var( $array, $k );
}
// add search weight
foreach ( $array as $k => $v ) {
// vars
$weight = 0;
$haystack = strtolower( $v );
$strpos = strpos( $haystack, $needle );
// detect search match
if ( $strpos !== false ) {
// set eright to length of match
$weight = strlen( $search );
// increase weight if match starts at begining of string
if ( $strpos == 0 ) {
++$weight;
}
}
// append to wights
$weights[ $k ] = $weight;
}
// sort the array with menu_order ascending
array_multisort( $weights, SORT_DESC, $array );
// remove key prefix
foreach ( array_keys( $array ) as $k ) {
$array[ substr( $k, 1 ) ] = acf_extract_var( $array, $k );
}
// return
return $array;
}