Categories
How To

Post Meta, Custom Post Meta, and Statistics

More fun with post meta, CMB2, statistics, and numbers.

I do a lot with weird stats. I do a lot with CMB2 and custom meta. I do a lot with CMB2 and weird post meta.

Is it any surprise I wanted to add my new year dropdown data to my site for some interesting statistics?

Of course not. But I started small. I have a saved loop called $all_shows_query

// List of shows
$all_shows_query = new WP_Query ( array(
	'post_type'       => 'post_type_shows',
	'posts_per_page'  => -1,
	'no_found_rows'   => true,
	'post_status'     => array( 'publish', 'draft' ),
));

This really just gets the list of all the shows and holds on to it. The meat of the code runs with this:

$show_current = 0;

if ($all_shows_query->have_posts() ) {
	while ( $all_shows_query->have_posts() ) {
		$all_shows_query->the_post();
		$show_id = $post->ID;
		if ( get_post_meta( $show_id, "shows_airdates", true) ) {
			$airdates = get_post_meta( $show_id, "shows_airdates", true);
			if ( $airdates['finish'] == 'current' ) {
				$show_current++;
			}
		}
		// More IF statements are here.
	}
	wp_reset_query();
}

As mentioned, there are more if statements, like if ( get_post_meta( $show_id, "shows_stars", true) ) {...} which gets data for if a show has a star or not. And if ( get_post_meta( $show_id, "shows_worthit", true) ) {...} which checks if a show is worth it or not. I was already doing a lot of this, so slipping in one more check doesn’t hurt.

To show the data, without Chart.js, it looks like this:

	<h3>Shows Currently Airing</h3>

	<p>&bull; Currently Airing - <?php echo $show_current .' total &mdash; '. round( ( ( $show_current / $count_shows ) * 100) , 1); ?>%
	<br />&bull; Not Airing - <?php echo ( $count_shows - $show_current )  .' total &mdash; '. round( ( ( ( $count_shows - $show_current ) / $count_shows ) * 100) , 1); ?>%
	</p>

With Chart.js, it looks like this:

<canvas id="pieCurrent" width="200" height="200"></canvas>

<script>
// Piechart for Currently Airing Data
var pieCurrentdata = {
    labels: [
        "On Air (<?php echo $show_current; ?>)",
        "Off Air (<?php echo ($count_shows - $show_current ); ?>)",
    ],
    datasets: [
        {
            data: [ <?php echo '
	            "'.$show_current.'",
	            "'.($count_shows - $show_current ).'",
	            '; ?>],
            backgroundColor: [
	            "#4BC0C0",
	            "#FF6384",
	            "#E7E9ED"
            ]
        }]
};

var ctx = document.getElementById("pieCurrent").getContext("2d");
var pieTriggers = new Chart(ctx,{
    type:'doughnut',
    data: pieCurrentdata,
    options: {
		tooltips: {
		    callbacks: {
				label: function(tooltipItem, data) {
					return data.labels[tooltipItem.index];
				}
		    },
		},
	}
});
</script>

Right now the data’s a bit off, since I’ve only updated 200 of the 325 shows, but it’s enough to get the information.