When running a blog, you often face the problem that you want to execute PHP code to customize your site. I love Quotes and want to realize a “daily Quote” on my page. I tried to do it without one of the numerous plugins since we normally don’t want additional plugin ballast, nor another plugin that has to be constantly updated. I’ve found some outdated customizations of the function.php file, but nothing of them worked. Since I will use PHP customization in the future, I decided to use a plugin named “PHP Code Widget”.
Let’s get into it.
After installing the plugin, you can use it as a normal text field, which can interpret the PHP Code.
As always, the first thing is a “hello world” to test if the code is working.
echo 'Hello World!';
After that, I thought about showing a random Quote each time a user opens the website. I have plenty of Quotes and will code them hard in that text field. No database. For that, I need a random number which will be the index for my Array.
int random_int ( int $min , int $max )
With an array, it could be looking like this. We need an array filled with quotes and an echo which chooses one of them. Reminder: array indices start with 0, that’s why I used “-1” after the Array count. I count the array because if I add or delete one, I don’t have to change the maximum random number.
$quotes = array( "Quote1", "Quote2", "Quote3" ); // Random Quote each time the site is refreshed echo $quotes[mt_rand(0, count($quotes)-1)];
My last edit was to put in the daily thing. With this code above you get a new quote each time you move through the website. I want to see a new one only each day. So we need a timestamp and modulo of all quotes as an index.
$quotes= array( "Fall down seven times - Get up eight.", "Stop wishing - start doing.", "Don't call it a dream, call it a plan." ); // Dayly Quote - one Quote for each day echo $quotes[date("dmY")%count($quotes)];
That’s it. Hope you like the new collection of my motivating quotes I’ve collected over the years 🙂