Streak Ended After 57 Days

My daily blogging streak finally came to an end on Sunday (I had to attend an event that day). I haven’t posted for last 2 days (Sunday and Monday). But I haven’t given up. Posts will keep coming in the future.

I’ll continue to write regularly going forward but it may not be every single day. While I knew this from the beginning, that it’d be difficult to write every day, I did my best to keep up and I’m proud of the streak that I achieved.

What’s next? I’ll focus a little more on my goal of contributing to WP related projects on GitHub. I’ll also try to make something useful. And I’ll use those experiences to write more on this blog. That’s all. Thanks for reading! 🙂

Creating An Alias For A Mac OS Terminal Command

Another busy day for a daily blog post. I’ll go with a short one today. It’s about creating an alias for running a terminal command.

For example, the terminal command open -a "Sublime Text can be run by a short keyword of our choice, say sub. It would also allow us to open a file directly by typing in sub filename.

This can be done by adding the following text in the .bash_profile file:

alias sub='open -a "Sublime Text"'

If .bash_profile file doesn’t exist, we can create one using touch command as follows:

touch ~/.bash_profile

We’ll also need to reload .bash_profile after making changes to it. It can be done by the source command as follows:

source ~/.bash_profile

Finally, entering sub will open Sublime Text and sub filename will open that file in the text editor.

This is a simple example, we can create other aliases too, but I hope you get the idea. Thanks for reading! 🙂

Edit: This may not work if you’re on a different shell like ZSH. To check what shell you are on, run echo $SHELL command. If it returns /bin/zsh, you can create a .zshrc instead of the .bash_profile file (and rest remains the same).

WP: Custom Post Type

By default we can create a post or a page in WordPress. These are basically WordPress post types. The good thing is we don’t necessarily restrict ourselves to just two of these. WordPress allows us to create our own custom post types.

Let’s say, we’d like to create a post type called “Events” and then create new posts under the custom post type called “Events”.

How do we do that? It’s quite simple. Let’s have a look at the code below which will help us achieve this goal.

<?php 

function ob_post_types() {
	register_post_type('event', array(
		'public' => true,
		'labels' => array(
			'name' => 'Events'
		),
		'menu_icon' => 'dashicons-calendar'
	));
}

add_action('init', 'ob_post_types');

?>

We have created our own function called ob_post_types which will be triggered automatically on the WordPress action hook called init.

Inside our function, we have a register_post_type, that registers the custom post type event and accepts an array of settings for this custom post type.

For example, is it publicly accessible? Yes. What labels does it have? One of the labels we’d like it to have is name (which is set to ‘Events’ in our example above). We’d also like to give it an icon by using something called dashicons in WordPress. We’ll see more about that in future posts.

For now, the code above, when added to functions.php of our newly developed theme, would render a custom post type called ‘Events’ in the site’s WP-Admin dashboard.

WP: Custom Queries

Custom queries in WordPress allow us to have a little more control over what we need.

For example, we could use a custom query to fetch posts from a certain category, with a certain post type and have it only display 2 posts per page. To do so we need to create a new query as follows:

$myPosts = new WP_Query();

This is object oriented programming, where we create a new object from a class. For example:

$dog = new Animal();
$cat = new Animal();
$dog->sleep();
$cat->run();

In the above example, objects (dog and cat) created from the class (Animal) will share the properties of that class. i.e. An animal can run, it can sleep and so on.

Similarly, in the first example in this post, we created an object called $myPosts that is created from the WP_Query class.

That alone isn’t sufficient. We need to modify the code a bit and customise it a bit by passing some arguments as follows:

$myPosts = new WP_Query(array(
	'posts_per_page' = 2,
	'category_name' = 'space',
	'post_type' = 'page'
	)); 

Now $myPosts has what we need but we haven’t printed it out yet. That can be done via the following code:

<?php

while( $myPosts->have_posts() ) {

	$myPosts->the_post(); ?>
	<p><?php the_title(); ?></p>

<?php } ?>

That’s it. This is a random example but I hope it helps to demonstrate how to form a simple custom WordPress Query.

WP: Trim Words

Today was another busy day. I’m writing this post in the last hour of the day to maintain the blogging streak.

This will be short post about fetching the content on your WordPress site and trimming it to a set number of words.

We know that the_content() function gets the content in the famous WordPress loop, but it displays everything from start to end.

If we need to fetch the content and display a set number of words, it can be done by using the following two functions:

  • get_the_content()
  • wp_trim_words(content, words)

To be specific, they can be used as follows:

echo wp_trim_words(get_the_content(), 18)

This will get the content, trim it to 18 words and echo it out on the screen. That’d be all in this post. Thanks for reading 🙂

WP: Register A New Menu Location

To register a menu location in our newly developed theme, we can include the following line in our functions.php file:

register_nav_menu('headerMenuLocation', 'Header Menu Location');

This again needs to be called on the action hook after_setup_theme (similar to the previous post where we added theme support for title).

Example:

function ob_theme_features() {
    register_nav_menu('headerMenuLocation', 'Header Menu Location');
    add_theme_support('title-tag');
}
add_action('after_setup_theme', 'ob_theme_features' );

Once this code is saved, we can see a “Menu” option under WP-Admin dashboard > Appearance page.

Trying to create a menu there will give us a prompt to select the menu location. We’ll be able to see a menu location that we just created (called “Header Menu Location” based on the code above).

Select that location and add some menu items like home page, blog page, etc.

Next we want to actually display this menu on the front-end. To do so, we’ll need to place the code below in one of the files responsible for outputting content on the front-end (e.g. index.php, single.php, etc).

We can put this in index.php to test it.

wp_nav_menu(array(
    'theme_location' => 'headerMenuLocation'
));

The result? You will start to see the menu you created by visiting the front page of your WordPress site.

You can read more about this by going to the official developer reference guide at WordPress.org 🙂

WP: Theme Support For Title

So far we’ve developed a theme that can load blog posts on the front page and allows us to open each post/article on it’s own independent perma(nent)-link.

But there’s one problem! We see the title of the page as a link as follows:

This can easily be fixed by adding theme support for title-tag using the add_theme_support WordPress function.

This function can be triggered on the action hook after_setup_theme as follows:

function ob_theme_features() {
	add_theme_support('title-tag');
}
add_action('after_setup_theme', 'ob_theme_features' );

Where does this code go? You must’ve guessed this already but if you’re new, it goes in functions.php file of our newly developed theme.

The result? We see a title instead of a link as follows:

Next, we’ll have a look at loading the WordPress admin bar in our theme.

WP: Enqueue Styles & Scripts

To Enqueue styles and scripts in WordPress, we add some piece of code in our theme’s functions.php file.

We’ve enqueued style.css in the previous post using wp_enqueue_style function. Let’s enqueue a script now and see how that’s done.

I have changed the functions.php code to the following:

<?php 

function ob_site_files() {
	wp_enqueue_style('ob_site_main_styles', get_stylesheet_uri());
	wp_enqueue_script('ob_site_main_script', get_theme_file_uri('/js/script.js'), NULL, '1.0', true);
	wp_enqueue_style('font-awesome', '//stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
}
add_action('wp_enqueue_scripts', 'ob_site_files');

To recap – We enqueue specific “style” and “script” by loading our function ob_site_files (which is triggered by an in-built WordPress action called wp_enqueue_scripts).

Line 5 and 6 are new in the code above.

Line 5 adds a script using wp_enqueue_script function that accepts (1) script name, (2) script URI, (3) dependencies, (4) version number and (5) a boolean argument which tells whether to enqueue the script before </body> instead of in the <head> (true loads it before the end of body tag).

Line 6 loads an external stylesheet (font-awesome). Note that we’re not adding any protocol (http or https) in there because wp_enqueue_style function will take care of that for us.

That’s how we enqueue styles and scripts the WordPress way.

WP: Head & Stylesheet

Based on the last few posts, we currently have the following files in our theme’s root directory:

/ob-test
    /style.css
    /index.php
    /header.php
    /footer.php

style.css

/*
Theme Name: OB-TEST
Author: Omkar Bhagat
Version: 1.0
*/

body {
    color: blue;
}

index.php

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

get_footer(); ?>

header.php

<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<p>This is header text</p>

footer.php

<p> This is footer text </p>
</body>
</html>

In the above setup, the code from the stylesheet doesn’t work. The content of the body doesn’t turn blue.

In WordPress, all the head data can be loaded in a different way, by using the wp_head() function. Therefore, our header.php can be changed to the following code:

<!DOCTYPE html>
<html>
<head>
	<?php wp_head(); ?>
</head>
<body>
	<p>This is header text</p>

The function we added takes care of loading scripts, stylesheets, etc but it doesn’t do that automatically. We need to do a couple more changes.

functions.php

The next thing to do there is to create functions.php file with the following code:

<?php 

function ob_site_files() {
	wp_enqueue_style('ob_site_main_styles', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'ob_site_files');

This is the meat and potatoes of this post. We create ob_site_files function that enqueues a new style by using the function wp_enqueue_style and gets the stylesheet via get_stylesheet_uri.

Next we add an action to trigger the load ob_site_files whenever wp_enqueue_scripts is loaded by WordPress.

This makes our stylesheet active. We know this because the body color changes to blue as follows:

And that’d be all in this post. We learned how to load stylesheet correctly in our newly developed WordPress theme.

WP: More On Header And Footer

In the previous post, we learned about using header.php and footer.php file to fetch and display header and footer on all site pages.

We basically achieved the following structure:

This can be made better by moving our HTML code from index.php to header and footer files, such that index.php only loads the content.

Here’s what needs to be done:

We move our HTML code till the beginning of the <body> tag to header.php and everything else from </body> to footer.php. We continue to fetch header and footer files to index (or any other page) via the getter functions like get_header and get_footer.

Now we don’t need to duplicate that piece of HTML on every page. Instead, we can focus on writing code that is specific to the page we’re working on (e.g. index.php, single.php, page.php, etc).