Ben Lobaugh Online


Category: PHP (Page 1 of 10)


Getting social media shares with php

Quick snippets to help me (and maybe you!) remember how to quickly and easily get share counts from social networks.

What other networks would you like to see?


function facebook_share_count( $post_id ) {
  $api = "";
  $url = $api . urlencode( get_permalink( $post_id ) );
  $response = wp_remote_get( $url );
  if( is_wp_error( $response ) ) {
    return 0;
  if( '200' != wp_remote_retrieve_response_code( $response ) ) {
    // Bad url
    return 0;
  $body = wp_remote_retrieve_body( $response );
  $body = json_decode( $body );
  if( isset( $body->shares ) ) {
    // Shares will not be set if there are none!
    return $body->shares;
  return 0;


NOTE: ***Twitter will be shutting down this API*** No replacement has been announced.

function twitter_share_count( $post_id ) {
  // Check for transient
  if ( ! ( $count = get_transient( 'twitter_count' . $post_id ) ) ) {
    // Do API call
    $response = wp_remote_retrieve_body( wp_remote_get( '' . urlencode( get_permalink( $post_id ) ) ) );
    // If error in API call, stop and don't store transient
    if ( is_wp_error( $response ) )
      return 'error';
    // Decode JSON
    $json = json_decode( $response );
    // Set total count
    $count = absint( $json->count );
    // Set transient to expire every 30 minutes
    set_transient( 'twitter_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
 return absint( $count );


function linkedin_share_count( $post_id ) {
  $api = '';
  $api .= urlencode( get_permalink( $post_id ) );
  if ( ! ( $count = get_transient( 'linkedin_count' . $post_id ) ) ) {
    $response = wp_remote_get( $api );
    if( is_wp_error( $response ) ) {
      // eat it
      return 0;
    // Should verify the correct json is returned
    $json = json_decode( wp_remote_retrieve_body( $response ) );
    $count = (int) $json->count;
    set_transient( 'linkedin_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
  return $count;

Book Review: PHPUnit Essentials

In the past few years I have worked on many projects that involved implementing a testing infrastructure, I have spoken at conferences on the important of and theories of testing, and I have led workshops training beginners in testing. In all that time I have looked for a good concise and easy to read resource to share with people. PHPUnit Essentials by Zdenek Machek meets and exceeds my expectations.

Machek starts the book out by walking through the available installation methods and then moves into tools, in particular IDEs. Several popular open source and commercial IDEs are reviewed including: NetBeans, Zend Studio, Eclipse, and PhpStorm. Machek walks through the process of setting up PHPUnit in each IDE and running simple tests to get you started.

Machek goes into the basics of testing but the real power of this book lies in the thorough review of the more advanced testing concepts that many resources shy away from. Starting with theory on how to write good testable code all the way to testing databases, the following topics are covered: dependencies, in depth command line usage, test isolation, dealing with globals and data providers, test organization, test doubles (fakes, stubs, mocks, expectations, and proxies), database testing, API testing, and testing legacy (spaghetti) code. As a bonus Machek tossed in chapters on functional tests in the web browser, continuous integration, behavior-driven testing, and even a section on PHPUnit alternatives.

This is a small book but it is packed with a powerful amount of information and excellent code examples. It is a must have on any PHP developers bookshelf.


Legal Stuff

Disclosure of Material Connection: I received this book free from the publisher Packt Publishing. I was not required to write a positive review. The opinions I have expressed are my own.

If you would like me to review your book head over to the contact page and get a hold of me.

PHP: Erase a value out of an array without knowing its key

If you find yourself with an array that you know contains a certain value that you need to access or erase here is a useful code snippet that I came across the other day.

$key = array_search( $needle, $haystack );
unset( $haystack[$key] );

For example, given the following array:

$colors = array( 'red', 'blue', 'green', 'yellow' );

If you wanted to get rid of ‘green’ but are unsure of its key:

$key = array_search( 'green', $colors );
unset( $colors[$key] );

Or you could change it to ‘brown’ with:

$key = array_search( 'green', $colors );
$colors[$key] = 'brown';

How to retrieve a usable date format from the Telligent REST API

Telligent’s Community Server has a REST API that allows developers to tap into almost every aspect of the database. While creating an importer for WordPress I was attempting to backfill posts with the correct publish date. Telligent provides the publish date through a field called PublishedDate, however in its default format the date is not very useful. The default date from the API looks similar to:


(Yes, including the slashes!)

WTF is that???

After spending a couple hours wrangling the data I finally got it to a place where it was close to the correct post time, however it was always off by a couple hours. This caused issues when rewriting inter-post links as the day of the post was sometimes incorrect, thus causing the year/month/day permalink to be invalid.

Then I found a hidden API parameter that solved all my issues…

Add UseIsoDateFormat=true to the the URL parameters and the following ISO date format will be returned:


From there it is easy peazy to convert it into any format you may need.

Happy hacking!

First Experiences with WebMatrix 2 and Windows Azure Website

WebMatrix is a free web development tool produced by Microsoft. WebMatrix is a complete development environment that not only provides a code editor, it also creates a new private instance of IIS Express to debug your project in, and downloads any dependencies your project may need, I.E. SQL Server Express, MySQL, PHP, etc.

I was asked what I thought of WebMatrix, however I have not spent a lot of time with it. I was working on a project that utilizes Windows Azure Web Sites and the App Gallery install of phpBB with another fellow. He was handling all the coding while I was administering the site through the web interface. I am now also coding for the site so I figured this is the perfect time to take WebMatrix for a spin..

Right off the bat I can tell you that if you are using Windows Azure Web Sites WebMatrix is a nice go to tool. WebMatrix is integrated with the Windows Azure Portal. Select your site from the Portal and there is a “WEBMATRIX” button on the toolbar. I did not have WebMatrix installed prior to starting this process. One-click of the button and WebMatrix was installed for me via Web Platform Installer.

Windows Azure Portal toolbar

Clicking the “WEBMATRIX” button automatically downloads the publish settings and sets up the WebMatrix environment for your project. Because WebMatrix understands phpBB it even pulled the PHP and SQL Server dependencies! The files and database were copied to my local machine. I am now able to interact with the phpBB web site through WebMatrix as an exact replica of the production website.

WebMatrix 2

WebMatrix even has a nifty tool that alerts you if you attempt to make changes to project core files.

WebMatrix 2 Alert

I made a few changes and clicked Run. My default browser opened and I was able to poke around the website as if it was running live. Satisfied that all seemed to be in working order, I clicked the Publish button a few minutes later. WebMatrix did a comparison of the files on the server to the local files to let me know which had changed. I could selectively choose which files to publish and which to retain. Even cooler, WebMatrix has an option to push back the entire database.

WebMatrix also supports code insight, or “Intellisense”, which is handy for finding class and function documentation throughout a project.

What is my verdict on WebMatrix? It seems to have matured into a great tool that is highly useful for web developers. Using Windows Azure Web Sites, or the WebMatrix Gallery you can, with a few clicks, have one of many popular open source content management systems (such as WordPress, Drupal, Joomla!) setup and running. The Publish feature eliminates the need for any additional applications to send files to the server. Additionally the automatic check of the server for changed files is very handy at ensuring only the proper files get uploaded or changed. Drawbacks? It currently only supports the Windows operating system.

Moving forwards I have a feeling WebMatrix will become my web code editor of choice, especially when working on Windows Azure related projects.

Page 1 of 10

Powered by WordPress & Drip City Coffee