Executing PHP within a WordPress text widget

Executing PHP within a WordPress text widget

I was looking for a way to add a dynamic check of the status of my Raspberry Pi to the sidebar of my website. A quick search of the WordPress plugin directory returned a plugin that would allow me to execute PHP code from within a text widget. Perfect for what I was thinking; A simple ping test to drive the dynamic text.

PHP Text Widget
Price: Free

After installing the plugin I created a new text widget and added the code below:

<?php
function pingAddress($ip)
{
 $pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
 if (0 == $status) {
 $status = "alive";
 echo ("<span style='font-weight: bold; font-size: 12pt'><img src='http://danielflannery.ie/wp-content/uploads/2015/11/rpi.png'/> Raspberry Pi is <span style='color: green;'>Online </span>:)</span><br>");
 
 echo ("<span style='font-size: 12pt'>Check it out <a href='http://pi.danielflannery.ie'></span><span style='color: red; font-size: 12pt'>here</span></a>.<br>");
 echo ("<span style='font-style: italic;; font-size: 10pt'>Might be slow, it's only a Pi.</span>");
 } else {
 $status = "dead";
 echo ("<span style='font-weight: bold;'><img src='http://danielflannery.ie/wp-content/uploads/2015/11/rpi.png'/> Raspberry Pi is <span style='color: red;'>Offline </span>:(</span><br>");
 }
}

pingAddress("http://pi.danielflannery.ie");
?>

This will try and ping the Pi to see if it is alive and alter the text output based on the reply.

<– You can see the code in action on the sidebar.

 

Leave a Comment