• 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.

Viewing 6 replies - 1 through 6 (of 6 total)
  • 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; ?>
    Thread Starter vestmar

    (@vestmar)

    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.

    <?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; ?>

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

    Thread Starter vestmar

    (@vestmar)

    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.

    Thread Starter vestmar

    (@vestmar)

    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.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘How to retrive a certain custom field form all post in a category and average’ is closed to new replies.