Adding a custom shortcode that prints track stat info

WavePlayer collects playback statistics of your audio tracks in a post meta_key called wvpl_stats. Every time a file is played back or downloaded or liked, WavePlayer register that event and updates the statistics of the track in the database.

In addition to displaying that data by using the appropriate placeholders in the info templates, you can create your custom code to retrieve and display that info wherever you like in your page templates.

The shortcode definition

The following code snippet shows an example of a custom shortcode that, after retrieving the wvpl_stats metadata of a given track, prints the info on the page.

add_shortcode( 'waveplayer_stats', 'waveplayer_stats_custom_shortcode' );
function waveplayer_stats_custom_shortcode( $atts ) {
	$html  = '';
	$pairs = array(
		'track_id' => '',
		'name'     => 'play_count',
	);
	$atts  = shortcode_atts( $pairs, $atts, 'waveplayer_stats' );
	if ( ! $atts['track_id'] ) {
		return $html;
	}
	
	$value = get_post_meta( $atts['track_id'], "wvpl_{$atts['name']}", true );
	if ( $value ) {
		$html = "$value";
	}
	
	return $html;
}

As an example, the previous shortcode can be used as follows:

[‎waveplayer_stats track_id="7956" name="downloads"]

where 7956 is the post ID of the audio attachment you want to get the statistics for.

You can easily customize line 17 to your preference, such as adding an icon or any additional CSS classes. For example, if you replace line 17 with the following code:

$html = "<span class=\"download-label fas fa-3x fa-download\">
	<span>$value</span>
</span>";

the shortcode will output something like this (assuming FontAwesome is active in your website):

913

The number of downloads shown above corresponds to the following track. You can easily confirm that by simply start downloading the following track and reloading this page in order to see that the number of downloads was incremented by at least one (other concurrent downloads may have occurred while you were visiting this page).

Once the [‎waveplayer_stats] shortcode is defined, you can use it also to get play_count, likes and runtime.

Powered by BetterDocs

0:00
0:00