How to Create a Random Quote / Fact WordPress Plugin
To create a WordPress plugin which shows a random value from an array, such as quote or fact, follow these steps.
Open your editor and create a file called fun_facts.php
(the name does not really matter). Then paste the following code:
<?php
/*
Plugin Name: Random Java Facts Plugin
Description: Displays a random interesting fact about Java.
*/
function java_facts_shortcode() {
$java_facts = array(
"Java was originally called Oak, but was renamed to Java in 1995.",
"Java was created by James Gosling at Sun Microsystems.",
"Java was first released in 1995.",
"Java is used by more than 3 billion devices worldwide.",
"Java is a class-based, object-oriented programming language.",
"Java is designed to be platform-independent, meaning it can run on any device with a Java Virtual Machine.",
"Java is used to develop desktop, mobile, and web applications.",
"Java is one of the most popular programming languages in the world.",
"Java is used by companies such as Google, Amazon, and Netflix.",
"Java is one of the few programming languages that is still actively developed and maintained."
);
$fact = $java_facts[rand(0, count($java_facts) - 1)];
$output = '<div class="java-facts-widget">';
$output .= '<h3>Did you know?</h3>';
$output .= '<p>' . $fact . '</p>';
$output .= '</div>';
return $output;
}
add_shortcode('java_facts', 'java_facts_shortcode');
?>
The above code creates a plugin for displaying Java fun facts. To display such facts, you have to use the short code [java_facts]
.
Next, save the file. Create a zip archive with this file. The file should be at the root of the archive.
Next, go to the admin interface and install a new plugin using the zip file you have just created.
You can start using the short code now. If you want to use it as a widget, you will have to edit the functions.php
file of your current WordPress template and allow short code there like this:
add_filter('widget_text', 'do_shortcode');
After that you can use it as a widget too and create a cool widget for your side panel.