WP: Shortcode To Display Page Template

Last two posts were about creating a WordPress shortcode and a WordPress page template, I’m going to mix these two and create a shortcode to display the page template I created in my previous post.

I’ve removed header and footer from the template code (taken from the previous posts) and edited the page-onedemo.php file as follows –

<?php 
/*
Template Name: One Demo Template
*/
?>
 
<?php 	$myposts = get_posts();
		foreach ($myposts as $post): ?>
		<li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 	endforeach; ?>

And I’ve added the following code (for creating short-code) using my custom functions plugin (e.g. Code Snippets):

function echo_hello_func() {
   	get_template_part('page-onedemo'); 
}
 
add_shortcode('echo-hello', 'echo_hello_func');

This does the job but with a small problem which you can see in the screenshot below:

We need the shortcode content to display exactly where the shortcode is placed. At the moment, we’re seeing it above the existing content. To fix this, we’ll need to use output buffer –

function echo_hello_func() {
    ob_start();
    get_template_part('page-onedemo'); 
    return ob_get_clean();
}
 
add_shortcode('echo-hello', 'echo_hello_func');

Doing so helps us to display the shortcode content in the right place –

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

WP: Create A Page Template

Let’s say I want to list down all the posts tagged with a keyword on a page. I could achieve this by creating something called a Page Template.

To do so, I’m going to my theme folder which is located at wp-content > themes > twenty-seventeen and then I’ll create a new page there using this rule: page-templatename.

Basic Page Template

The new page that I created is page-onedemo.php and it has the following content –

<?php 
/*
Template Name: One Demo Template
*/
?>
 
<p> TEST PAGE </p>

I’m now going to create a new page inside admin dashboard > pages and select template as One Demo Template as follows:

Opening this page in the browser gives this result:

Page Template With Posts

It doesn’t do much but it’s a good start. Now I’m going to show a list of posts using the following code:

<?php 
/*
Template Name: One Demo Template
*/
get_header(); ?>
 
<?php 	$myposts = get_posts();
		foreach ($myposts as $post): ?>
		<li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 	endforeach; ?>
 
<?php get_footer(); ?>

To break it down, here’s what it does (step by step):

  • Get posts and store inside $myposts
  • Then loop through $myposts and fetch each post as $post
  • Fetch time, link and title of $post
  • End for loop

And here’s the result of that:

With Header And Footer

To beautify this result, I can look into page.php inside my current theme’s folder and make adjustments as follows:

<?php 
/*
Template Name: One Demo Template
*/
get_header(); ?>
 
<div class="wrap">
	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">
 
<?php 	$myposts = get_posts();
		foreach ($myposts as $post): ?>
		<li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php 	endforeach; ?>
 
		</main><!-- #main -->
	</div><!-- #primary -->
</div><!-- .wrap -->
 
<?php get_footer(); ?>

This gets me header and footer and beautifies the result as follows:

That’s all in this post! 🙂

WP: Create A Shortcode

Do you know about shortcodes in WordPress? It’s basically some text that you can add between square brackets and it turns into some feature on the front-end.

In this post, let’s look at how to create a shortcode in WordPress. It’s quite simple and the example below explains how we can create a simple shortcode called echo-hello

function echo_hello_func() {
 	return 'Hello Hello Hello';   
}
 
add_shortcode('echo-hello', 'echo_hello_func');

This code can be added to your theme’s functions.php file or via a third party plugin like code-snippets.

Once done, you will be able to add [echo-hello] shortcode in your posts/pages which will basically print Hello Hello Hello on the front-end.

We can of course do more complex stuff with it but I hope this gives you a basic idea on how to create a shortcode on a WordPress site.

10 Common Git Commands

Here are some common git commands that I use on a regular basis to create pull requests on GitHub –

1. Shows all remotes
git remote

2. Shows remotes with their url
git remote -v

3. Gets remote data into local repo but doesn’t add to your working files
git fetch <remote>

4. Merge fetched data
git merge <remote>/master

5. Fetch and merge remote data with our working files
git pull
OR
git fetch <remote>
git checkout master
git merge <remote>/master

6. Add a remote
git add remote <name> <url>

7. Add remote branch as a local branch
git checkout --track <remote>/<branch_name>

8. Delete a branch locally
git branch -d <branch_name>
git branch -D <branch_name> force delete

9. Delete remote branch
git push <remote_name> --delete <branch_name>

10. Create and checkout a branch
git checkout -b <branch_name>

Bonus

I know I said 10 in the title but here are some more –

11. Rebase current branch with another branch.
git rebase <branch_name>

This will “port” another branch (Branch A) into the branch where you are currently working (Branch B), by applying all of your unique commits from Branch B on top of Branch A and replacing Branch B with this revised version. That way, you can “catch up” to other branches by re-writing git history in your local git. [Source]

12. See commits in current branch that aren’t cherry picked to master
git cherry -v master

13. Push a branch to remote
git push <remote> <branch>
git push <remote> <branch> -f force push

That’s all for now. If you’d like, go ahead and bookmark this page as I may add more to it in the future.

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! 🙂