Skip to content

Instantly share code, notes, and snippets.

@undfine
Forked from logoscreative/functions.php
Last active April 19, 2024 14:55
Show Gist options
  • Select an option

  • Save undfine/8f97c9ffabf22152f9a4e146bd7fdf24 to your computer and use it in GitHub Desktop.

Select an option

Save undfine/8f97c9ffabf22152f9a4e146bd7fdf24 to your computer and use it in GitHub Desktop.
Pods Shortcode orderby 'meta_value_num'
<?php
/**
* WordPress stores all meta fields as strings, which causes problems for ordering by numbers. When using Pods::find() directly, this issue can be addressed by casting the field as a decimal, as shown here: https://github.com/pods-framework/pods-code-library/blob/master/example/classes/Pods/find/examples/orderby-number.php
*
* In shortcodes, this strategy is not possible, as MySQL functions can not be used in the WordPress post editor. Instead, you can use the "pods_shortcode_findrecords_params" params filter, as shown below:
*/
/**
* Example to order by a price field properly.
*/
//SHORTCODE example: [pods name="property" orderby="price.meta_value_num DESC" template="listings"]
add_filter( 'pods_shortcode_findrecords_params', 'slug_orderby_by_number_pods_shortcode', 10, 2 );
function slug_orderby_by_number_pods_shortcode( $params, $pod ) {
if ( isset( $params[ 'orderby' ] ) && strpos($params[ 'orderby' ], 'meta_value_num') ) {
// get the SORT order, Default value (ASC)
$sort = strpos($params[ 'orderby' ], 'DESC')? 'DESC' : 'ASC';
// remove the SORT, to be appended later
$params[ 'orderby' ] = str_replace(['DESC','ASC', 'desc','asc'], '', $params[ 'orderby' ]);
// cast the meta_value as a number (decimal) add sorting
$params[ 'orderby' ] = 'CAST(' . $params[ 'orderby' ] . ' AS DECIMAL) ' . $sort;
}
return $params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment