• Welcome to Tux Reports: Where Penguins Fly. We hope you find the topics varied, interesting, and worthy of your time. Please become a member and join in the discussions.

Summation of meta_values from the meta table

This entry is part of a series of entries "2017 WordPress Tips & Tricks"
calculator.png


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

PHP:
<?php
   $args = array(
   'posts_per_page'   => 5,
   'offset'           => 0,
   'category'         => '',
   'category_name'    => '',
   'orderby'          => 'date',
   'order'            => 'DESC',
   'include'          => '',
   'exclude'          => '',
   'meta_key'         => '',
   'meta_value'       => '',
   'post_type'        => 'post',
   'post_mime_type'   => '',
   'post_parent'      => '',
   'author'       => '',
   'author_name'       => '',
   'post_status'      => 'publish',
   'suppress_filters' => true
);

$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:
$args = array('meta_key' => 'post_views_count');
$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:
$counts = array();
foreach ($posts as $post) {
  array_push( $counts, get_post_meta( $post->ID, 'post_views_count', true ) );
}

$viewTotals = array_sum($counts);

var_dump($viewTotals);
  • Like
Reactions: Goodfella and robru

Blog entry information

Author
LPH
Views
1,926
Last update

More entries in Technology

More entries from LPH

Top