• I found a resolved topic, here, that does something real close to what I would like to do. But, I would like to restrain this to only posts of a certain category and with certain tag.

    Does anyone know how I would limit the following code by category and tag? Right now it is adding up all of the values in the database tables with the custom value field.

    <?php
    $miles = array();
    $meta_key = 'abc';//set this to your custom field meta key
    $miles = $wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
    echo 'Total miles is '.array_sum( $miles );
    ?>
Viewing 7 replies - 16 through 22 (of 22 total)
  • If only this is all correct!!

    <?php
    $miles = array();
    $meta_key = 'abc';//set this to your custom field meta key
    $my_tag = 'TagName'; //set this to your tag name - case sensitive
    $my_cat = 'MyCategory';
    $miles = $wpdb->get_col($wpdb->prepare(
    "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s
       AND post_id in
          (SELECT a.object_id FROM wp_term_relationships a, wp_term_taxonomy b, wp_terms c
           WHERE a.term_taxonomy_id = b.term_taxonomy_id
           AND b.term_id = c.term_id
           AND b.taxonomy = 'post_tag'
           AND c.name = %s)
       AND post_id in
          (SELECT a.object_id FROM wp_term_relationships a, wp_term_taxonomy b, wp_terms c
           WHERE a.term_taxonomy_id = b.term_taxonomy_id
           AND b.term_id = c.term_id
           AND b.taxonomy = 'category'
           AND c.name = %s)", $meta_key,$my_tag,$my_cat));
    echo 'Total miles is '.array_sum( $miles );
    ?>
    Thread Starter Kahil

    (@kahil)

    It returned a value of zero

    Did you make sure you matched the meta_key, tag name, and category name exactly as shown in the database? If not, a value of zero will be returned.

    Can you test each of the SELECT queries using phpMyAdmin (or similar) to be sure you have each one correct?

    Thread Starter Kahil

    (@kahil)

    They are correct. I’ve done this before. I can get it to show a sum, but only for either the tag or the category…I can’t figure out how to get it to narrow it down by both factors.

    If both of the SELECT object_id subqueries works to give the correct list of object_id’s, make sure that they have id’s in common. If they do, I am at a loss to explain the result.

    I am out of ideas – sorry.

    Thread Starter Kahil

    (@kahil)

    Ok…I have another idea that maybe someone could help me with on this…

    ok…what if I give this section an ID. Is there a way to create a form of sort that would add up the values of each occurrence of that ID?

    I am trying to do the same thing but without the sum. I just want a list of unique meta_key values for a given category (the current category).

Viewing 7 replies - 16 through 22 (of 22 total)
  • The topic ‘Add up the values of custom fields…’ is closed to new replies.