• thunderdust

    (@thunderdust)


    Hi Guys,

    Currently I have “two categories” with both the same “custom field”

    Category: Cat01 / Cat02
    Custom field: Test01

    What I want is the get the average value that is stored in custom field “Test01”, but from a specific category, being CAT01

    Is this possible, and if so, please help out a newbie.

    Thnx ??

Viewing 1 replies (of 1 total)
  • vtxyzzy

    (@vtxyzzy)

    Here is sample code showing how to do this:

    $category_name = 'CAT01';
    $meta_key = 'Test01';
    $sql = "
    select avg(pm.meta_value)
    from $wpdb->postmeta pm
    join $wpdb->posts p on p.ID = pm.post_id
    where pm.meta_key = '$meta_key'
    and p.ID in (
       select ID from $wpdb->posts p2
       join $wpdb->term_relationships tr on p2.ID = tr.object_id
       join $wpdb->term_taxonomy tt on
         (tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'category')
       join $wpdb->terms t on (t.term_id = tt.term_id and t.name = '$category_name')
       )
    ";
    $avg = $wpdb->get_var($sql);
    echo "<p>AVERAGE $meta_key = $avg </p>";
Viewing 1 replies (of 1 total)
  • The topic ‘Average of Custom Field linked to Category’ is closed to new replies.