write to custom field using sql statement (3 posts)

  1. everten2
    Posted 5 years ago #

    Is it possible to write a value to a custom field using a sql statement during the loop or other means?

    I have 5 custom fields that contain numbers. I want to calculate the average of these numbers and write it back to the database into a 6th custom field.

    Is this advisable? How will it affect performance of the website?


  2. MichaelH
    Posted 5 years ago #

    Saw your other thread with a similar question. http://wordpress.org/support/topic/366035?replies=1

    Guess the question is, what are you going to do with the data once it is saved? If the data is for display, then just calculate it on the fly.

    If you have to save the data, then will need to use the save_post and publish_post filters, but that's beyond me--look at a plugin such as More Fields for idea on how to handle that.

    I'm going to close your other post and point it to this thread.

  3. everten2
    Posted 5 years ago #

    I want to sort by the average. I have already been able to calculate and display the average on the fly by doing the following in the loop:

    $rating1 = get('customfield1');
    $rating2 = get('customfield2');
    $rating3 = get('customfield3');
    $rating4 = get('customfield4');
    $rating5 = get('customfield5');

    $totalRatings = $rating1+$rating2+$rating3+$rating4+$rating5;
    $totalVotes = 5;
    $average = $totalRatings / $totalVotes;

    My ultimate objective is to be able to sort posts based on the the average.

Topic Closed

This topic has been closed to new replies.

About this Topic