How to tell whether a user meta value has increased or decreased

I store a custom user meta value for my users that is stored as a number like a score. I need a way of telling whether it has decreased or increased from its last value. So when I display it I can show an arrow to show which it’s trending. Any ideas?

Here is how I get the score and update the user meta.

add_filter('the_content','update_user_score');
function update_user_score($content){
    global $post;
    $author_id = $post->post_author;
    $author_posts = get_posts( array(
    'author' => $author_id,
    'posts_per_page' => -1
  ) );
    $counter = 0;
    foreach ( $author_posts as $author_post )
  {
    $score = get_post_meta( $author_post->ID, 'ratings_score', true );
    $counter += $score;
  }
    update_user_meta( $author_post->post_author, 'score', $counter);
    return $content;
}

Related posts

Leave a Reply

2 comments

  1. I would solve this creating two extra Custom Fields:

    • _score_last
    • _score_variation

    The first underscore makes the CF invisible in the Admin area.

    Drop the following code in your theme’s functions.php:

    if( is_admin() )
    {
        add_action( 'save_post', 'wpse_57217_check_customfield_variation', 11, 2 );
    }
    
    function wpse_57217_check_customfield_variation( $post_id, $post )
    {
        if ( 
            ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            or ! current_user_can( 'edit_post', $post_id )
            or wp_is_post_revision( $post )
        )
        { // Noting to do.
            return;
        }
    
        $actual = get_post_meta($post_id, 'score', true);
        $last = get_post_meta($post_id, '_score_last', true);
        $last = ( '' != $last ) ? $last : '0';
        if ( '' != $actual ) 
        {
            if ( absint($actual) > absint($last) )
            {
                update_post_meta( $post_id, '_score_variation', 'up' );
            }
            elseif ( absint($actual) == absint($last) )
            {
                update_post_meta( $post_id, '_score_variation', 'stable' );
            }
            else
            {
                update_post_meta( $post_id, '_score_variation', 'down' );
            }
            update_post_meta( $post_id, '_score_last', $actual );
        } 
    }
    

    And for reference only, this inside the loop:

    echo 'actual score: ' . get_post_meta($post->ID, 'score', true);
    echo '<br> last score (value already updated): ' . get_post_meta($post->ID, '_score_last', true);
    echo '<br> score variation: ' . get_post_meta($post->ID, '_score_variation', true);
    
  2. Simple – you need 2 separate meta values, one for current score, one for either last score or score trend. With a single value stored, WordPress has no way of knowing anything but that value – no way to tell if it’s the first time it’s been set or the millionth time.