WordPress.org

Ready to get started?Download WordPress

Forums

How to retrive a certain custom field form all post in a category and average (7 posts)

  1. vestmar
    Member
    Posted 1 year ago #

    Hello guys and gurus :)

    I have a custom field in all my posts in all the categories on my site, the name is "cp_price".

    So I would like to "read" that custom field's valuea (it is a price) from all the posts in a category and make an average out of them and display it on the website.

    Can I do this with a widget?

    Thank you kindly for all the sugestions for this!

    Puiu.

  2. justingreerbbi
    Member
    Posted 1 year ago #

    Seems like something you may have to code yourself.

    This is a rough estimate of what I would do. This is not tested

    <?php
    $my_query = new WP_Query('category_name=special_cat'); 
    
    $prices = array();
    $price;
    
    while ($my_query->have_posts()) : $my_query->the_post();
    
    // GET THE CUSTOM PRICE AND PLACE IT IN AN ARRAY
    array_push($prices,get_post_meta($post->ID,cp_price,true));
    
    foreach($prices as $single){
    	$price = $single + $price;
    	}
    
    // GET THE AVERAGE
    $average = count($prices) / $price;
    
     endwhile; ?>
  3. vestmar
    Member
    Posted 1 year ago #

    Justin, thank you, that was FAST! :)

    Since I am only in the very begining of php, could you tell me how the code would change if for example I would be interested in the average of the cp_price custom field from all the posts in the category that has the ID=50?

    Thank you, if you pass Romania, drop by for a coffee :)

    Puiu D.

  4. justingreerbbi
    Member
    Posted 1 year ago #

    <?php
    $my_query = new WP_Query('cat=50'); 
    
    $prices = array();
    $price;
    
    while ($my_query->have_posts()) : $my_query->the_post();
    
    // GET THE CUSTOM PRICE AND PLACE IT IN AN ARRAY
    array_push($prices,get_post_meta($post->ID,cp_price,true));
    
    foreach($prices as $single){
    	$price = $single + $price;
    	}
    
    // GET THE AVERAGE
    $average = count($prices) / $price;
    
     endwhile; ?>
  5. justingreerbbi
    Member
    Posted 1 year ago #

    Remember I have not tested this but it will get you on the right track

  6. vestmar
    Member
    Posted 1 year ago #

    Ok, thank you.

    All I have to read now is how to adapt a piece of code to be able to use it in a widget (copy/paste).

    Thank you very J,
    your coffee is waiting ;)

    Puiu D.

  7. vestmar
    Member
    Posted 1 year ago #

    Justin,

    One more question: because I don't see divs or classes in your code, is there a need for css for what you sugested?

    Thank you!

    Puiu D.

Topic Closed

This topic has been closed to new replies.

About this Topic