WP: The Loop

Building on top of the previous post, let’s go ahead and add the famous “WordPress Loop” to the index.php of our theme. It’ll help to fetch and display blog posts on the site.

In the previous post, we had the following code in index.php

<?php
    bloginfo('name');
    bloginfo('description');
?>

Let’s change that to –

<h1> <?php bloginfo('name'); ?> </h1>
<p> <?php bloginfo('description'); ?> </p>
 
<?php

while (have_posts()) {

	//fetches post, keeps track of count
	the_post();
	?> 
 
	<h2> <?php the_title(); ?> </h2>
	<p> <?php the_content(); ?> </p>

	<?php
}
?>

The code above fetches blog name and wraps it in h1 header. It also fetches blog description and wraps it in p paragraph tag.

Next, it goes into the while “loop”.

The while loop there checks have_posts() function. If it returns true, it’ll continue to execute everything inside of it.

Inside the while loop, we have the_post() function which fetches the post data and keeps track of the count. This allows us to use functions like the_title() and the_content() to output the title and content of the blog post.

It continues to do so as long as there are posts. This means changing our new theme’s index.php file to the code above will output all the blog posts on the site.

WP: Blog Title & Description

In the previous post, we created a simple WordPress theme. It doesn’t do much. It just displays “Hello WorldPress” on the site.

It can display anything we like. For example, it can print names. To do so, we’ll need to modify index.php and use the following code in it –

<?php
	function welcome($person) {
		return "Welcome $person";
	}
	echo welcome('Bob');
	echo welcome('Alice');
	echo welcome('Eve');
?>

The PHP function above, called welcome(), accepts a variable $person and returns “Welcome” followed the content of that variable (in this case, that’s the name of the person).

Thus, the line welcome('Bob'), will echo out “Welcome Bob” on screen.

Similarly, there are some WordPress functions which we can use to echo (or print) out the blog title and description. The code below does exactly that.

<?php
	bloginfo('name');
	bloginfo('description');
?>

That’s all in this short post! 🙂

WP: Hello World Theme

In the previous post, we created a simple WordPress plugin. In this post, let’s create a simple Hello World WordPress theme that you can upload and install to your WordPress site.

Folder Structure

Let’s call our theme “Simple Hello World Theme” and let’s create a folder that will contain all our theme files. Let’s call this folder “shw-theme”.

We’ll also need three basic files to create our basic theme. Our folder structure would look like this –

/shw-theme
    /index.php
    /style.css
    /screenshot.png

index.php

<?php 
	echo 'Hello WorldPress'; 
?>

style.css

/*
Theme Name: Simple Hello World Theme
Author: Omkar Bhagat
Version: 1.0
*/

screenshot.png

The screenshot.png could be any image file that you’d like to use as your theme’s thumbnail image. The resolution of this image can be found in the official WordPress.org documentation. As of now the recommended image size is 1200px wide by 900px tall.

Zip It!

Next zip the folder and the theme is ready to upload. It does nothing special. It only prints out “Hello WorldPress”.

WP: Hello World Plugin

In this post, let’s look at how to create a simple “Hello World” plugin in WordPress. By “Hello World” I mean a “basic” plugin that does nothing special but you can upload and install it on your WordPress site.

Creating The Plugin

The first step is to create a plugin folder and plugin file with the plugin name. Let’s name our plugin hello-world-replace.

This means our folder structure would look like this: hello-world-replace > hello-world-replace.php.

Enter the following code in the main plugin file hello-world-replace.php

<?php 
/*
Plugin Name: Hello World
Plugin URI: https://csmumbai.com
Description: This plugin replaces all instances of "hello" with "Hello World"
Author: Omkar Bhagat
Version: 1.0
*/
 
function hello_world_replace( $text ) {
	return str_replace( 'hello', 'Hello World', $text );
}
 
add_filter('the_content', 'hello_world_replace');
 
?>

Save the file. Zip the folder. And the plugin is ready!

Testing The Plugin

To test the plugin, go to your site’s WP-Admin dashboard > Plugins > Add New and upload this zipped file.

Next create a post with hello text inside of it and publish it. Check the published version and you’ll find hello will be turned into Hello World.

That’s all in this post! 🙂

Python: Unit Tests

One way to write unit tests in Python is by using Nose Tools. If you don’t have it installed, it can be done via command line by typing in pip install nose in the terminal.

from nose.tools import assert_equal

def solution(num1, num2):
    return num1+num2

class SolutionTest(object):
    
    def test(self, sol):
        assert_equal(sol(2,2),4)
        assert_equal(sol(4,4),8)
        
        print("All test cases passed")
        
# run tests
t1 = SolutionTest()
t1.test(solution)

In the code above, we import assert_equal from nose.tools. The function solution below it accepts two numbers and returns their sum.

Then we have a class SolutionTest that has a test function accepting self and sol as two arguments to it.

The assert_equal function then checks whether the output of its first argument is equal to the second. e.g it checks whether sol(2,2) equals to 4.

Our code above returns “All test cases passed” as the output.

However, if we modify the code to assert_equal(sol(2,2),4), it’ll return AssertionError: 5 != 4.

Using this basic idea, you can implement unit tests in Python. Thanks for reading! 🙂

CSS: Display None

Today was quite a busy day for me. It’s 8 PM and I’m falling behind on my goal of publishing a post on this blog.

Since I have very little time on my hands, I’ll share a quick tip on CSS. It’s super useful. In fact if you had to remember just one thing about CSS, remember this. You will use it all the time, especially if you’re a web engineer.

Ok! The one that that I’m referring to is a CSS property called display:none;. Using this you can hide HTML elements from the web page.

The above GIF shows this property in action. I have used Google Chrome’s dev tools to demonstrate that. To open Chrome dev tools, just right click on any element on screen and hit inspect element.

You can then also hit the shortcut CMD+SHIFT+C to switch to selection tool and use your cursor to select any item on the screen.

That’s all for today! 🙂

30 Day Blogging Streak

Yesterday I completed a 30 day blogging streak on this blog. While this is no big deal, it is pretty cool because I could keep up with my goal of writing something everyday and making it a habit.

The idea was to show up each day and write something useful. As mentioned in the first blog post on this blog, I did my best to avoid perfection paralysis. I did so by writing each day and pushing posts out even if they weren’t good enough.

I could do so much better by using screenshots and creating cool illustrations but instead of doing all that, I just pushed those out as soon as possible, without trying to make them perfect.

They’re not great but also not terrible. I said to myself, as long as the output isn’t bad, I’ll publish it. This made me achieve a 30 day blogging streak, something I failed to do since 2012 (past 7 years).

Next

Note: When I started, I didn’t exactly plan on publishing a post every day. I know that isn’t a sustainable long term goal. I actually thought of writing for 10 minutes each day (something that I can do long term with or without my laptop or an internet connection).

I’ll continue to try and push posts out as soon as possible but I know there will be days where I won’t be able to keep up. On those days, I’ll fall back to the goal of “write something 10 minutes a day”.

If I don’t have 10 minutes, I’ll get it down to 5 minute and then 1 minute. The idea is to produce something, even if that means writing just one line or one word.

Ok! With that said, I don’t wish to slack off today. Here’s a bonus “useful” thing that I’d like to add to this post –

Bonus

You can check for open ports for a site by using the nmap tool in terminal. For example: nmap csmumbai.com will return the following result –

Omkars-iMac:~ omkarbhagat$ nmap csmumbai.com

Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-21 12:09 IST
Nmap scan report for csmumbai.com (192.0.78.25)

Host is up (0.047s latency).
Other addresses for csmumbai.com (not scanned): 192.0.78.24
Not shown: 998 filtered ports

PORT    STATE SERVICE
80/tcp  open  http
443/tcp open  https

Nmap done: 1 IP address (1 host up) scanned in 23.37 seconds

If nmap isn’t installed on your computer, you can get it from https://nmap.org/download.html. If you’re on a Mac and have Xcode installed, I believe nmap should come with it.

That’s all in this post. Thanks for reading! 🙂

WP: Install WordPress Locally

There are different ways to install WordPress locally. Some of the popular ways are listed below. WordPress can be installed locally via –

  • MAMP (Mac, Apache, MysQL, PHP)
  • WAMP (Windows, Apache, MySQL, PHP)
  • XAMP (Cross-platform, Apache, MariaDB, PHP, Perl)
  • VVV (Varying Vagrant Vagrants)

Tutorials for the same can be found on their official sites or around the web (Google it). In this post, I’ll just cover one of the ways to install WordPress (which is by using MAMP).

For this, you’ll need to download MAMP and WordPress on your Mac computer. Next, install MAMP and run it.

Create a folder in your home folder, say wpdev and extract WordPress in there. Here’s how it will appear –

Next, open MAMP preferences, goto General tab and change the document root to the new folder we created, which is wp-dev.

Next, start all servers in MAMP (from the front/main screen which you see when you open MAMP).

This will open http://localhost:8888/MAMP/ in your web-browser. If it doesn’t, you can open it manually.

Next go to tools > phpMyAdmin > Databases. Enter a database name, say testdb1 and hit the create button.

Finally go to http://localhost:8888/wordpress/ where you will see a page to start installing WordPress. Go through the setup and enter the following database details when asked:

Once done, you’ll be asked for site details like site title, admin username/pass, etc. With that your WordPress installation will be complete.

Finally, you can access your site’s wp-admin dashboard at http://localhost:8888/wordpress/wp-admin/

That’s all! You have successfully installed WordPress on your local machine.

Python: Find Nth Last Node In A Linked List

The goal is to find Nth last node in a given linked list. This can be done by using an imaginary stick.

A stick can be imagined in code by using left and right pointers.

# Problem: Getting Nth to last node in LinkedList
# Logic: Use a stick with two pointers

def find_nth_node(n, node):
    
    left_pointer = node
    right_pointer = node
    
    for i in range(n):
        
        if right_pointer:
            right_pointer = right_pointer.next
        
    # right_pointer is now n nodes ahead
    
    while right_pointer:
        left_pointer = left_pointer.next
        right_pointer = right_pointer.next
        
    return left_pointer

# Testing the result

a = Node(1) #0 -- default right_pointer value
b = Node(2) #1 -- first iteration
c = Node(3) #2 -- second iteration - right_pointer gets here after being n nodes ahead
d = Node(4) #3
e = Node(5) #4

a.next = b
b.next = c
c.next = d
d.next = e

find_nth_node(2, a).value # second last node's val is 4

The first for loop in the code brings our right_pointer in position (n steps ahead of left_pointer), thus creating our imaginary stick.

Once that’s in place, we are ready to find the Nth last node.

The second for loop keeps moving the left_pointer and the right_pointer to the next node as long as the right_pointer points to some node. It stops once it points to Null or None (which is at the end of the Linked List).

The above can be imagined as our stick moving across the given Linked List with left_pointer and right_pointer moving to the right one step (one node) at a time.

Once the second for loop stops, the right_pointer will point to None (the end of the Linked List). Since the length of the stick is N, we can safely say our left_pointer is now pointing at Nth last node.

Therefore printing the value of the node pointed by the left_pointer gives us the value of Nth last node.

In the example given above, the Nth last node (the second last node) is 4.

A Good Bad Password

Disclaimer: This is not the ideal way to generate a password. The best way to generate a good and strong password is by using password manager apps. Read more about this in my previous post here.

This is an OKAY way to quickly generate a memorable password and can be used for less serious online accounts or throwaway online accounts that are in no way connected to your other important accounts like Gmail, Facebook, etc.

I don’t recommend this but it is much better than using “test”, “root”, “admin” or “pass123” type of passwords.

Ok! Now that I have clarified what this is about, let’s look at how to generate a good bad password.

The Good Bad Formula

I suggest the following quick and dirty formula to generate a password/passcode:

capital_letter + first_three_char_of_service_name + symbol + numbers

For example, if I had to generate a password for a throwaway reddit account using the formula above, it would be:

  • Capital Letter: O
  • First three characters of a service name: red
  • A symbol: #
  • Numbers: 892

The result: Ored#892

I’d always remember this password because I could always generate it just by looking at the service name (which is reddit in this case).

Again, I don’t recommend this for all your passwords. For serious, sensitive and important stuff, please use a password generator app and follow the security measures listed in my previous post.