Google Trends is a service that queries the popularity of specified keywords. Google Trends analyzes a portion of Google web searches to calculate how many times the user’s input terms have been searched, comparing the results against total search volume over time. It then displays the results in a chart — a search volume graph drawn on a linear scale.
This article provides a method to embed Google Trends charts directly into WordPress pages or posts using shortcodes.
Here’s the code:
/*
Plugin Name: WordPress Shortcode for Google Trends Chart
Plugin URI: https://imzl.com/wordpress-shortcode-google-trends.html
Description: Embed Google Trends charts in WordPress using shortcodes
Version: 0.1
Author: Len Chou
Author URI: https://imzl.com/
*/
function wps_trend($atts) {
// Parse shortcode attributes with default values
extract(shortcode_atts(array(
'w' => '500', // Width
'h' => '330', // Height
'q' => '', // Query keywords
'geo' => 'US', // Geographic location
), $atts));
// Input formatting
$h = (int)$h;
$w = (int)$w;
$q = esc_attr($q);
$geo = esc_attr($geo);
ob_start(); // Start output buffering
<script type="text/javascript" src="http://www.google.com/trends/embed.js?hl=en-US&q=<?php echo $q; ?>&geo=<?php echo $geo; ?>&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=<?php echo $w; ?>&h=<?php echo $h; ?>"></script>
return ob_get_clean(); // Get and return buffer contents
}
add_shortcode("trends", "wps_trend"); // Register shortcode
Installation:
Save this code as a .php file, upload it to the wp-content/plugins directory, then activate the plugin from the admin panel. If you prefer not to use it as a plugin, paste the code into your current WordPress theme’s functions.php (when pasting into functions.php, make sure to remove the opening <?php on the first line, otherwise your site will crash).
Using the Shortcode
You can now use shortcodes to embed Google Trends charts. Example:
[trends h="450" w="500" q="wordpress+themes+wordpress+plugins" geo="CN"]
The code above displays a chart for WordPress themes and plugins in China, with a height of 450 and width of 500. To customize the dimensions, modify the values as noted in the code.