Home Programming WordPress: Execute custom code in a post without plugins

WordPress: Execute custom code in a post without plugins

by Kliment Andreev

I wanted to run a custom code from a WordPress post and I was looking around. I’ve found a nice plugin but it was running PHP only. It’s not that I needed more, but I stumbled when I tried to combine HTML elements and the PHP script with this plugin. So, at the end I’ve found a much more elegant solution, that pretty much runs any code. All I had to do is to embed the HTML page as an object.

So, let’s say I have a custom code in a PHP page called test.php that’s in the root of my WordPress installation. All is needed is this code in WordPress (use the Text tab, not Visual).

<object data="https://blog.andreev.it/test.php" width="800" height="600"></object>

And this is how my test.php page looks like. I won’t comment the code, but it has an input label and a button. Type a hostname and it will ping it and then render the output as an HTML array.


If you are executing code that needs root access, this solution won’t work, because the code runs under the Apache username (which normally is not root).

.error {color: #FF0000;}

// define variables and set to empty values
$hostErr = "";
$host = "";

  if (empty($_POST["host"])) {
    $host = "Host is required";
  } else {
    $host = test_input($_POST["host"]);
    // only letters and numbers are allowed
    if (!preg_match("/^[a-zA-Z0-9.]*$/",$host)) {
      $hostErr = "Only letters and numbers allowed";

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;

<h2>Online ping (ICMP) probe</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
  Host: <input type="text" name="host" value="<?php echo $host;?>">
  <span class="error">* <?php echo $hostErr;?></span>
  <input type="submit" name="submit" value="Submit">

                echo "<h2>Output:</h2>";
                echo $host;
                echo "<br>";
                exec("ping -c 3 $host", $output, $status);
                echo '<pre>';
                echo '<pre>';



The code in action. Type some host on the internet (e.g www.whatever.com), click the button and see the result.

Related Articles

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More