• I’ve got two metakey (metaA and metaB).
    It’s possible to get a list of post sorted by the sum of the metaA value + metaB value??
    I’ve find a method to do it using a custom query but with a query_posts() will be really nice.
    Thanks
    Luca

Viewing 2 replies - 1 through 2 (of 2 total)
  • Dan Bissonnet

    (@asinglehumanbeing)

    The only option I can think of is to create a hidden ‘sum’ meta field that is automatically updated when the post is updated and then sort on that.

    There are a couple of action hooks you could use: update_post_meta & updated_post_meta which fire before and after updating the meta values. I would take a bit of coding but it should be hook into those and update the third ‘sum’ field when either of the other two are updated.

    Look in wp-includes/meta.php at the update_metadata function to get an idea of how those hooks work.

    You can do it using filters on the query:

    The filters can go in functions.php or in the template ahead of the query (I would put them in the template at least while testing).

    function mam_posts_fields ($fields) {
       global $mam_global_fields;
       if ($mam_global_fields) $fields .= ", $mam_global_fields";
       return $fields;
    }
    function mam_posts_join ($join) {
       global $mam_global_join;
       if ($mam_global_join) $join .= " $mam_global_join";
       return $join;
    }
    function mam_posts_orderby ($orderby) {
       global $mam_global_orderby;
       if ($mam_global_orderby) $orderby = $mam_global_orderby;
       return $orderby;
    }
    add_filter('posts_fields','mam_posts_fields');
    add_filter('posts_join','mam_posts_join');
    add_filter('posts_orderby','mam_posts_orderby');

    This part has to go in the template:

    $mam_global_fields = 'SUM(metaA.meta_value, metaB.meta_value) as meta_sum';
    $mam_global_join = "JOIN $wpdb->postmeta metaA ON (metaA.post_id = $wpdb->posts.ID AND metaA.meta_key = 'metaA')
       JOIN $wpdb->postmeta metaB ON (metaB.post_id = $wpdb->posts.ID AND metaB.meta_key = 'metaB')";
    $mam_global_orderby = " meta_sum ASC";
    // Your query_posts goes here
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘sort posts by a sum of two metakey values’ is closed to new replies.