1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Summation of meta_values from the meta table

The summation of meta_values in the post meta was accomplished through the get_posts, array_push, and array_sum.
Categories:
  1. calculator.png

    The get_posts function has many arguments which allow a developer to pull from the meta table.

    PHP:
    1. <?php
    2.    $args = array(
    3.    'posts_per_page'   => 5,
    4.    'offset'           => 0,
    5.    'category'         => '',
    6.    'category_name'    => '',
    7.    'orderby'          => 'date',
    8.    'order'            => 'DESC',
    9.    'include'          => '',
    10.    'exclude'          => '',
    11.    'meta_key'         => '',
    12.    'meta_value'       => '',
    13.    'post_type'        => 'post',
    14.    'post_mime_type'   => '',
    15.    'post_parent'      => '',
    16.    'author'       => '',
    17.    'author_name'       => '',
    18.    'post_status'      => 'publish',
    19.    'suppress_filters' => true
    20. );
    21.  
    22. $posts_array = get_posts( $args );
    The meta_key and meta_value are two that I used today to pull the post_view_counts used by the Newspaper theme. I wanted to add up all the values and combine them with the forum message views.

    First, the meta_key was used to return an array of posts with values.

    PHP:
    1. $args = array('meta_key' => 'post_views_count');
    2. $posts = get_posts( $args );
    Next, I pushed the meta values into an array then used array_sum to add up the values for a total of views.

    PHP:
    1. $counts = array();
    2. foreach ($posts as $post) {
    3.   array_push( $counts, get_post_meta( $post->ID, 'post_views_count', true ) );
    4. }
    5.  
    6. $viewTotals = array_sum($counts);
    7.  
    8. var_dump($viewTotals);
    Goodfella and robru like this.

Comments

To make a comment simply sign up and become a member!