Select meta_value between limits

This code was written for a user to select posts based on the value of a Custom Field between min and max limits.

Note that a key-prefix is hard-coded into the example, and that a couple of debugging statements have been left in the code.

// Define the function that will create the join string
function mam_custom_field_range($keyname='',$min=false,$max=false) {
  global $mam_global_join,$wpdb;
  if ($keyname && (is_numeric($min) || is_numeric($max))) {
    $mam_global_join .=
      " JOIN $wpdb->postmeta acfr_$keyname ON
      ( $wpdb->posts.ID = acfr_$keyname.post_id
        AND acfr_$keyname.meta_key = '$keyname'";
    if (is_numeric($min)) $mam_global_join .= " AND acfr_$keyname.meta_value >= $min";
    if (is_numeric($max)) $mam_global_join .= " AND acfr_$keyname.meta_value <= $max";
    $mam_global_join .= ')';
  }
}
// Define the join filter function
function mam_posts_join ($join) {
   global $mam_global_join;
   if ($mam_global_join) $join .= $mam_global_join;
   return $join;
}
// Add the filter to the hooks
add_filter('posts_join','mam_posts_join');

// Call the function to create the join and run the query
mam_custom_field_range('mykey',55.01,222);
echo "
DEBUG join: $mam_global_join";
query_posts('caller_get_posts=1');
echo "
DEBUG request: $wp_query->request";
echo "
";
if (have_posts()) {
   while (have_posts()) {
     the_post();
     echo "
$post->post_title";
   }
} else {
  echo "
<h3>No posts found</h3>
";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*