function getPinterestCount() { $url = get_permalink(); $json_string = file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url='.$url); $json = json_decode($json_string, true); return intval( $json['count'] ); } Code (markup): Hi guys, please help me check and fix the following code, I can’t understand why it couldn’t work. Thanks!
"Couldn't work" doesn't tell us anything. What's it doing or not doing and what are you expecting it to do?
I'm using this code for wordpress. And when display it as <?php echo getPinterestCount(); ?> it always show " 0 ". I'm using the same code for Twitter, Linkedin. They're showing well but doesn't work for Pinterest.
This is an example of when you need to check the output of each line of your function and see why the following line isn't working properly. It's a simple enough process to show that the data returned by Pinterest isn't a valid json encoded string Below works: <?php var_dump(getPinterestCount('http://google.com')); function getPinterestCount($url = '') { $url = empty($url) ? get_permalink() : $url; $json_string = file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url='.$url); $raw_json = preg_replace('/^receiveCount\((.*)\)$/', "\\1", $json_string); $json = json_decode($raw_json, true); return intval( $json['count'] ); } PHP: Feel free to check the output for yourself.
But my code worked well for Linkedin and Twitter ( I'm using Wordpress ) and doesn't work with Pinterest :|
As I said, the returned output of the Pinterest API by itself isn't a valid json encoded string. You have to do a bit of parsing first.