In this short tutorial, we will learn to how to create a simple WordPress plugin step by step and to have the plugin activated from the WordPress dashboard. Important names are highlighted to help ease the tutorial navigation.
To write a calculator WordPress plugin, follow these steps:
- Set up the plugin structure:
- Create a new directory inside the wp-content/plugins directory of your WordPress installation. Name it something like calculator-plugin.
- Inside the calculator-plugin directory, create a new file named calculator-plugin.php. This will be the main plugin file.
- Open the calculator-plugin.php file in a text editor and add the following code to set up the plugin:
<?php
/**
* Plugin Name: Calculator Plugin
* Plugin URI: https://www.example.com/calculator-plugin
* Description: Simple calculator plugin for WordPress.
* Version: 1.0.0
* Author: Your Name
* Author URI: https://www.example.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
// Plugin code goes here - Define the plugin functionality: Inside the calculator-plugin.php file, add a function that will handle the calculator functionality. For example:
<?php
function calculator_shortcode($atts) {
// Shortcode logic goes here
} - Register a shortcode: Still inside the calculator-plugin.php file, add the following code to register a shortcode that will be used to display the calculator:
add_shortcode('calculator', 'calculator_shortcode'); - Implement the calculator logic: Inside the calculator_shortcode function, implement the calculator logic using HTML and PHP. For example:
<?php
function calculator_shortcode($atts) {
ob_start();
?>
<form action="" method="POST">
<input type="number" name="num1" placeholder="Enter number 1" required>
<input type="number" name="num2" placeholder="Enter number 2" required>
<select name="operation" required>
<option value="+">Addition</option>
<option value="-">Subtraction</option>
<option value="*">Multiplication</option>
<option value="/">Division</option>
</select>
<button type="submit">Calculate</button>
</form>
<?phpif ($_SERVER['REQUEST_METHOD'] === 'POST') {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];$result = 0;switch ($operation) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
$result = $num1 / $num2;
break;
}echo "<p>Result: $result</p>";
}return ob_get_clean();
} - Save the calculator-plugin.php file.
- Activate the plugin:
- Log in to your WordPress admin dashboard.
- Go to the “Plugins” page.
- Find the “Calculator Plugin” in the list of plugins and click “Activate”.
- Use the calculator shortcode:
- In the WordPress editor, create a new page or post where you want to display the calculator.
- Add the following shortcode to the content area:
[] - Save or publish the page.