WP: Header & Footer

In this post we’ll add a header and footer to the theme we created before. This can be done by creating header.php and footer.php files and then calling them by get_header() andget_footer() functions respectively.

Example: Let’s create a header.php file with the following content:

<p> This is header text </p>

And footer.php as follows:

<p> This is footer text </p>

Save both these files in the theme’s root folder (next to index.php). And finally edit index.php to include those “getter” functions as follows:

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

<?php get_header(); ?>
  
<?php
 
while (have_posts()) {
 
    the_post(); ?> 
  
    <h2> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2>
    <p> <?php the_content(); ?> </p>
 
    <?php
}

get_footer();

?>

If we load the site’s front page now, it’ll get us the following result:

Moving header and footer in separate files allows us to customise these files independently.

Prettify Your Code

Today is busy day for me and so I’ll write a short (but useful) post. It’s about prettifying your code. Prettifying is basically formatting your code and making it neat and tidy. It can be a task if you do it manually but you don’t have to. Modern text-editors allow you to do this automatically.

If you use a text-editor, there’s a chance that it allows you to install third-party extensions.

I personally use Sublime Text. To install any extension (or package) in Sublime, you need to hit CMD+SHIFT+P and enter “install” in the search bar.

It’ll give you some options, out of which you need to choose “Package Control: Install Package”.

After you choose that, just type in “pretty” and you’ll get some suggestions. You can use any of those, depending on what language you use to code.

I use a couple of packages but my default (and favorite) one is HTML-CSS-JS Prettify. This package, once installed, will allow you to prettify your code by selecting it and hitting the CMD+SHIFT+H shortcut on the keyboard.

Other text-editors also offer this feature (e.g. Atom). Note: This is actually common knowledge but I really wanted to get a post out today 🙂

WP: Single.php

Disclaimer: The title of this post isn’t a “relationship status” 😉 It is instead a file that WordPress uses to display single posts on the site.

As seen before, the famous WordPress loop can be used in index.php to fetch and display all the posts on the site.

<h1> <?php bloginfo('name'); ?> </h1>
<p> <?php bloginfo('description'); ?> </p>
  
<?php
 
while (have_posts()) {
 
    the_post(); ?> 
  
    <h2> <?php the_title(); ?> </h2>
    <p> <?php the_content(); ?> </p>
 
    <?php
}
?>

This loop gets us the following result on the front page of the site (when our theme is active):

Home Page (fetching posts via the famous WordPress loop)

This displays all the posts on the front page but we’d like to have an option to open each one separately.

To do so, let’s modify our code and wrap the title in a tag with href pointing to the_permalink() which fetches the permanent link of the respective post.

<h1> <?php bloginfo('name'); ?> </h1>
<p> <?php bloginfo('description'); ?> </p>
  
<?php
 
while (have_posts()) {
 
    the_post(); ?> 
  
    <h2> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></h2>
    <p> <?php the_content(); ?> </p>
 
    <?php
}
?>

The result? Each post title becomes a link that allows us to open the post at a unique URL –

Home Page displaying all the posts (with their title as links)
The screen we see after opening one of the posts

Notice that the title is still a link. It doesn’t have to be, especially when we’ve already opened the post.

To fix this, let’s create another file called single.php in our theme’s folder and add the index.php code in there (without the permalink part).

<h1> <?php bloginfo('name'); ?> </h1>
<p> <?php bloginfo('description'); ?> </p>
  
<?php
 
while (have_posts()) {
 
    the_post(); ?> 
  
    <h2> <?php the_title(); ?> </h2>
    <p> <?php the_content(); ?> </p>
 
    <?php
}
?>

Now when we open any post, its title won’t be a link.

Single Post (where title isn’t a link anymore)

What’s happening here? Previously index.php was taking care of all the pages on the site. Now index.php is only taking care of the front page while single.php is taking care of all the web pages that are “posts” on the site.

The same can be done for web pages that are “pages” on the site by using page.php file in the theme’s folder.

This allows us to customise home page, single posts and single pages separately while developing a WordPress theme.

WP: Delete Plugin Data On Uninstall

In the previous post, I created a plugin which stores some data in the database. Now I will add some code to it which will help to delete this data when the plugin is deleted or uninstalled via the plugins page.

When a plugin is deleted, the uninstall hook is called. I’m going to register the uninstall hook and ask it to call a function which removes our plugin data for us. Here’s the code for it:

register_uninstall_hook( __FILE__, 'my_fn_uninstall' );
function my_fn_uninstall() {
    delete_option( 'g_first_option' );
    delete_option( 'g_second_option' );
}

I’ve added this to the noice-plugin.php file I created in the previous post. If I try to delete the plugin now, it will display this message to me:

Once I hit OK, it will delete g_first_option and g_second_option from the wp_options table in the database.

WP: Add A Form To The Plugin Admin Page

In the previous post, I created a plugin page. And now I’ve added a form to it with the help of the following code:

<?php 
/*
Plugin Name: Noice Plugin
Plugin URI: https://csmumbai.com
Description: This plugin is Noice!
Author: Omkar Bhagat
Version: 1.0
*/ 
 
add_action('admin_menu', 'noice_create_menu');
 
function noice_create_menu() {
	add_options_page('Noice Plugin Title', 'Noice Plugin Settings', 'administrator', __FILE__, 'noice_settings_page');
}
 
function noice_settings_page() {
    echo '<h2>Hello Noice Person!</h2>';
?>
 
<form method="post" action="options.php">
 
    <table class="form-table">
 
        <tr>
        <th>First Field: </th>
        <td><input type="text" name="g_first_option" value="<?php echo get_option('g_first_option'); ?>" /></td>
        </tr>
 
        <tr>
        <th>Second Field: </th>
        <td><input type="text" name="g_second_option" value="<?php echo get_option('g_second_option'); ?>" /></td>
        </tr>
 
    </table>
        
    <p class="submit">
        <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
    </p>
 
</form>
 
<?php } ?>

The lines which have been changed or added are highlighted in the code above. This gets us a form as follows:

At this point it does nothing because I’m yet to register these fields. In other words, WordPress doesn’t know what to do with these fields when the form is submitted.

<?php 
/*
Plugin Name: Noice Plugin
Plugin URI: https://csmumbai.com
Description: This plugin is Noice!
Author: Omkar Bhagat
Version: 1.0
*/ 
 
add_action('admin_menu', 'noice_create_menu');
 
function noice_create_menu() {
    add_options_page('Noice Plugin Title', 'Noice Plugin Settings', 'administrator', __FILE__, 'noice_settings_page');
    add_action( 'admin_init', 'noice_form_settings' );
}
 
function noice_form_settings() {
    register_setting('noice_form_settings_group', 'g_first_option');
    register_setting('noice_form_settings_group', 'g_second_option');
}
 
function noice_settings_page() {
    echo '<h2>Hello Noice Person!</h2>';
?>
 
<form method="post" action="options.php">
 
    <?php settings_fields('noice_form_settings_group'); ?>
 
    <table class="form-table">
 
        <tr>
        <th>First Field: </th>
        <td><input type="text" name="g_first_option" value="<?php echo get_option('g_first_option'); ?>" /></td>
        </tr>
 
        <tr>
        <th>Second Field: </th>
        <td><input type="text" name="g_second_option" value="<?php echo get_option('g_second_option'); ?>" /></td>
        </tr>
 
    </table>
        
    <p class="submit">
        <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
    </p>
 
</form>
 
<?php } ?>

Here’s a short explanation of this code:

  1. Line 14: Added a way to call noice_form_settings function as admin_init is the action hook which is triggered before any other hook when a user accesses the admin area.
  2. Line 17-20: Registering the form fields with WP
  3. Line 28: This puts some hidden fields in the form to check if the request is valid. More on this here and here.

Entering something in the form and saving it returns this page:

The options will stay there even if I deactivate and reactivate the plugin. That’s fine but I’ll need to remove the data when the plugin is deleted/uninstalled. I’ll work on that in a future post.

Note: I can find this data in the database by going to wp_options table.

WP: Create A Plugin Admin Page

To create a WordPress plugin admin page, I’ll need to first add a menu item in the WP-Admin dashboard.

Instead of creating a totally new item using add_menu_page, I’m going to add my menu item under Settings option with the help of add_options_page function as follows:

<?php 
/*
Plugin Name: Noice Plugin
Plugin URI: https://csmumbai.com
Description: This plugin is NOICE!
Author: Omkar Bhagat
Version: 1.0
*/ 
 
 
// ONE
add_action('admin_menu', 'noice_create_menu');
 
// TWO
function noice_create_menu() {
	add_options_page('Noice Plugin Title', 'Noice Plugin Settings', 'administrator', __FILE__, 'noice_settings_page');
}
 
// THREE
function noice_settings_page() {
    echo '<p>Hello, this is a Noice Plugin!</p>';
}
 
?>

Here’s what I basically did:

  1. Added an action hook for admin_menu to call noice_create_menu
  2. noice_create_menu creates an options page for us with the following arguments:
    1. Page Title
    2. Menu Item Name
    3. Who can access it?
    4. Slug name (I used the file name here).
    5. Function to call to output content on the page
  3. noice_settings_page outputs content on the page

This results in the following menu item under the Settings option in WP-Admin dashboard –

And clicking on this new menu items takes me to –

Notice three things here:

  1. Output content – Hello, this is a Noice Plugin!
  2. Page title in the tab – Noice Plugin Title
  3. And the slug at the end of the URL – noice-plugin.php

This results in a simple WordPress admin page that prints some text. Let’s see how to do more with this in the next post.

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.