• Hi!

    I’m building a site that lists products that have a custom field “value1”. So I have a custom post type ‘product’ and it has two taxonomies ‘brand’ and ‘model’.

    When I’m in custom taxonomy archive page i would like to get the highest value1 in that taxonomy. I have found this code:

    function max_meta_value(){
    global $wpdb;
    $query = "SELECT max(cast(meta_value as unsigned)) FROM wp_postmeta WHERE meta_key='value1'";
    $the_max = $wpdb->get_var($query);
    return $the_max;
    }

    That gives me the highest value1 of all products. So how should i modify that to get the highest value1 of that taxonomy I am viewing?

    I’m a novice in SQL queries and i have tried a lot of different commands there without any luck. So basically i would just need some help figuring out how to add some lines to that query so i can add it to my archive page template like this for exaple:

    max_meta_value($brand,$model)

    I appreciate all the help i can get! So if you know your way around the SQL query commands i would be more than happy to hear how it should be done ??

Viewing 6 replies - 1 through 6 (of 6 total)
  • Thread Starter brutex

    (@brutex)

    Thanks Joy!

    I checked it out and got the function to return the array of the tax query but I have no idea how to combine that to the max_meta_value() function that is getting the highest value of all posts :/

    Hi,
    @brutex

    I have created the solution for this, code is below, Hope it may help you
    also, you can change variables according to your requirement.

    Put this code in your custom taxonomy archive page.

    $term_id = get_queried_object()->term_id;
    
    $products = get_posts(array(
      'post_type' => 'product', //put post-type slug here
      'post_status' => 'publish',
      'numberposts' => -1,
      'tax_query' => array(
        array(
          'taxonomy' => 'product_cat', //put taxonomy slug here
          'field' => 'id',
          'terms' => $term_id,
          'include_children' => true
        )
      )
    ));
    
    $value1 = array();
    foreach($products as $product){
    	$product_id = $product->ID;
    	$value1[] = get_post_meta($product_id,'value1',true); // mata key = value1
    }
    
    $max_price = max($value1); // result

    Thanks.

    Thread Starter brutex

    (@brutex)

    Thanks @chinteshprajapati !

    I actually made something like that yesterday too. I run it through a new WP_Query though. Foreach might be faster and lighter?

    Hi,
    @brutex

    I think WP_Query is more faster and reliable.

    Thanks.

    Thread Starter brutex

    (@brutex)

    @chinteshprajapati OK then I will keep it like it is now! Thank you!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Getting the maximum custom field value inside taxonomy term’ is closed to new replies.