Author: Khanh



Is it Gif or Jif?

On a lighter topic today, I want to share with you a story of my childhood. Back in the 90s, the very first image I downloaded onto my computer (downloading images and saving them on your hard drive was a big thing back then), was an animated gif of all 151 Pokemon. It took me forever because the image had to load before I could download it. But really, it was because I was on a 14kb connection. But when it did finish loading and I got it onto my hard drive, that thing was boss.

From the get-go, I pronounced Gif with a hard G. And continued pronouncing it that way all the way up into my college years, unbeknownst that Steve Wilhite, the creator of the Gif format, said it was pronounce with a soft G, or “Jif”. One of my college professors told us this in a dark, musty lab filled with dust and the deafening hum of computer fans.

“It’s pronounced ‘Jif’, a soft G. Almost like a J. That’s what Wilhite said and he invented it. That’s how you should be pronouncing it from now on.”

Along with this proclamation, he launched into appropriate times to use a Gif and inappropriate times. But I was still reeling from the knowledge that I had been wrong almost my entire life. As time went by, Gifs became less and less relevant and for a while, it seemed like the format was on its way out. But in recent years, Gifs have made something of a comeback, being used for lightweight technical animations and–of course, amusing animated looping videos. I don’t think the format is going to see the boom that it did back in the 90s, but it’s not without its charm and usage now.

Of course, that brings me back to my conundrum. Ever since college, I had banished the pronunciation of Gif with a hard G and forced myself to pronounce it with a soft G. Only people have tended to band together and pronounce the word with a hard G. Even the dictionaries say that both pronunciations are accepted. Even the White House says it’s pronounced with a hard G. And amongst all this is Steve Wilhite, who once again said that you pronounce Gif like “Jif” in more recent years at the Webby Awards (is anyone else surprised by how fancy the Webby Awards are?) It’s true. See?

In the grand scheme of things, does it really matter how you pronounce the stupid word so long as you know what it is? Probably not. But how one pronounces Gif has been a debate that’s raged on since the format was first released. After all 1) Technically, they’re both correct. 2) It really doesn’t matter.

As for me, I might have to reprogram myself to say it with a hard G. Even knowing the historical naming of the format (peanut butter, for real), I can’t bring myself to keep saying it with a soft G. Here’s a great article about why people generally veer towards the hard G version and why it’s technically more accurate as a hard G than a soft G: How to Really Pronounce GIF.



The Difference Between Deprecated, Depreciated, Obsolete

OK, laugh all you want, but I used to think deprecated was depreciated. Never had an issue with obsolete, but I recently felt a little better about myself when an acquaintance and much more experienced programmer used “depreciated” instead of deprecated to describe something. It made me wonder if anyone else had the same confusion I did.

My problem started with English and my perceived understanding of words–and my attitude towards looking up words in the dictionary. My style has always been, “Word I don’t recognize? Eh, I’ll just assume its meaning within the context of the sentence/paragraph”. You see, I hadn’t ever really used the word deprecated before I got into development. To me, it always meant: “To disapprove of something”. Which is technically accurate, if somewhat vague. The word didn’t mean enough to me, like it was too general to use in a programming context to describe something that was outdated, being replaced or out of fashion. I was wrong (obviously).

Which is why I thought depreciated was the correct word, which to me seemed to mean more like, “something that’s worth less as time goes on”. Which I looked up prior to dropping the word from use when describing aging programming practices because it seems to be geared towards the value or worthiness of something. While it’ll still work in a lexical sense (don’t look at me, I’m not a writer–certainly not a technical one anyway), I can understand why more people use deprecated instead.

So here, the difference between deprecated, depreciated and obsolete as they related to development and programming. And when to use each so you never have an embarrassing moment again…

Deprecated: Something is becoming outdated, or slowly being phased out. Often, a deprecated practice or element is still in use, but it is encouraged to stop using it as it may become obsolete in the next iteration or release. An example of a deprecated HTML element is the <center> tag.

Depreciated: Something is being reduced in value over a period of time. The homes on Mount Terrible are worth less year after year, it means their property values are depreciating.

Obsolete: No longer being used, dropped from standards. The HTML <blink> tag is obsolete and should not be used anymore, tragically.

So there you have it. Three words. Two of which beginning developers and programmers get mixed up now and then.



Bonfire: Reverse a String Solution

It seems my previous Bonfire post has been fairly popular, so I figured I might as well share some of my other solutions in case someone might find it useful. This time, I’m tackling the Bonfire prior to the Factorializing one.

These solutions aren’t necessarily the best, most efficient way of solving the Bonfires. They’re just my approach to the problem. Within programming, coding and development, there’s usually multiple ways to solve the same problem. And depending on the philosophy of the coder, they might view certain approaches as more ideal than others. I’m just presenting what I have in case it helps someone.

Approaching the Problem

So the Free Code Camp Bonfire starts us off with the following code:

function reverseString(str) {
  return str;
}

reverseString('hello');

Already we see that we need to use a function that takes a parameter of str. Str in the function call has a value of “hello”. So, we are going to have to figure out how to reverse the string, “hello”. Having gone through the old Free Code Camp (they updated their lessons sometime in late-August) track that involved moving through Codeacademy’s JS course, we’ve encountered this problem before.

What I did for that solution was I separated the string by the letter and loaded them into an array. From that array, we can rebuild the string but backwards this time using a for loop. While this works, it’s hardly efficient and has us writing a ton of convoluted code to do something relatively simple.

Here’s what exists within JS to allow us to do this more efficiently. There are three pre-made functions within JS: split(), reverse() and join(). We can combine all three of these to quickly split up the string into an array that will resemble: [h, e, l, l, o], reverse it and turn it into [o, l, l, e, h], then join it back into a string: “olleh”.

The Immutable String Issue

Why do we need to turn the string into an array? Strings in JS are immutable. Immutable elements cannot be modified after they have been created.

So in the above code, str is set to a string that says “hello”. We cannot actually modify hello because it is immutable. That means, we can’t even do something as simple as reverse the string. To get around this, you have to turn the string into an array, reverse the array, then join the array back into a string. Because you join the array back into a string that will then say “olleh”.

Reversing the String & Returning It

Now we need to do all this in one step and on the str parameter. To combine functions you use the . (dot) operator. So it should look like this:

return str.split('').reverse().join('');

The above code is doing exactly what I said in the previous section. It is taking whatever str is, splitting it into an array. Then it reverses the array, then joins the array back into a string. Using a pre-built function allows us to sidestep the messy exercise of writing a loop.

So overall, this is what the final code looks like:

function reverseString(str) {
  return str.split('').reverse().join('');
}

reverseString('hello');

All this gets returned outside the function and the console in the Bonfire should return “olleh” and validate all the conditions.

Resources

Ten Ways to Reverse a String in JS, Edd Man
Really good resource for exactly what we’re facing in this Bonfire. It also includes the above solution using pre-built functions as well as a few other approaches using various loops. And one example using recursion if you really felt like it.

How Do You Reverse a String in Place in Javascript, StackOverflow
Excellent resource and discussion on how to reverse a string.



Do You Suck at Math? Learn to Program Anyway

There’s something to be said for being good at math. Or at least not sucking at it. I suck at it, and playing catch up after all these years of doing very little with math also sucks. I would be lying if I said I still hated it as much now as I did back then. In high school there was no class I loathed more than math class. It was a one to two hour horrorfest every weekday when I’d sit there and watch my peers fly through the material while I struggled to keep up. It felt like I was never going to understand what was going on. Part of that was how it was taught, which isn’t an indictment on my teachers not caring or not being good at what they did. They were good people, excellent at their professions. It was me. Some of us learn things differently. It wasn’t until a couple of years ago did I realize that how I was taught math wasn’t the best way for me to learn it.

I learned math through trying to learn to program, because a lot of programming tutorials, books and courses have a lot of math-based examples. So while I was trying to figure out the language, I was also forced to figure out why we were doing certain things with the language. And because I wanted to learn the programming, one of the byproducts was figuring out some of the math–because I had to. Now, I’m still not good at math. And if you ask me to calculate something, my first response is probably to go ask someone else. But, I’m no longer of the opinion that it’s one of those things that I’ll never get the hang of–music, on the other hand, I’m perfectly happy to continue sucking at that for the rest of my life.

I read a couple of interesting opinion pieces recently. One was Al Sweigart’s, “‘How much math do I need to know to program?’ Not That Much, Actually”, which explores some of the most commonly used math-related concepts in programming and Sarah Mei’s, “Programming is Not Math”. Whether one agrees with the ideas put forth in either article is various. I’m of the opinion that knowing math and being good at it definitely helps. And if a Computer Science or Computer Engineering degree is where you want to go with it, then having a solid grasp on math is definitely needed. Knowing math is also incredibly useful when it comes to certain programming tasks too. But I have personally found that what I picked up while learning to program is all that I’ve needed. And if I need to solve more complex programming tasks, the math that comes along with it tends to be learned in the process of figuring out the code.

I don’t think math is a prerequisite for programming, certainly not if you’re just aiming to learn to program. Where if you couldn’t cut it in calculus then you would never survive the process of learning to code. I also don’t think people should discourage those who aren’t great at math from trying to learn how to program anyway. After all, a lot of people successfully learn through a mixture of interest and determination and I definitely think a lot of people pick up the math as they pick up the language.

Resources

Project Euler
Programming challenges to solve math-related problems. Great for practice when you need something to expand your horizons.

How to Think Like a Computer Scientist
by Jeffrey Elkner, Allen B. Downey, and Chris Meyers



How to Enable Experimental Chrome Features

There are a lot of reasons why you want to enable experimental Chrome features, whether you’re a developer looking to stay on the cutting edge of new technologies or a user who just wants to see the latest and greatest things. Enabling experimental features in Chrome will allow you to preview some of the awesome new things out there.

There are a few downsides to enabling experimental features, browser instability is one of them and security and privacy concerns are another. So understand that there are definitely some downsides when you turn experimental features on. Let’s get to actually doing it now.

How to Enable Experimental Chrome Features

1) In your Chrome browser’s address bar, enter chrome://flags/ then hit enter.

chromegl

2) You’ll be taken to a page listing all the experimental features available that you can enable or disable at a whim. One of the features that I tend to like keeping on is the Experimental Web Platforms option. Simply click on the Enable link:

webplat

4) Once you click on the Enable link, a button will appear in the bottom left of your browser telling you to Relaunch Chrome. You should Enable all the features you want before Relaunching by clicking the button.

relaunchchro5) Once relaunched, your experimental feature(s) should be enabled now.

Disabling Experimental Chrome Features

Disabling experimental features can be done in pretty much the same way as enabling them.

1) In your Chrome browser’s address bar, enter chrome://flags/ then hit enter.

2) Locate and click on the Disable link on all the features you want to turn off.

3) Click on the Relaunch Now button to reload Chrome and turn those features off.

Again, be aware that not all experimental features are stable, some can present security risks or even cause data corruption. It’s recommended to turn on only those experimental features that you will use, and once you stop using them, turn them off. In the mean time, check the resources links to see some cool experimental features you can play around with.

Resources

10 Experimental Features You Need to Try, BlogThinkBig
TechAdvisory, 5 Experimental Chrome Features



Bonfire: Factorialize a Number Solution

I’m going through FreeCodeCamp’s coding track as a way to brush up on Javascript, and re-familiarize myself with its more programming-centered features. I have been using Javascript primarily with websites. Most of the time, I’m not dealing with anything beyond timing, detecting user actions and maybe a little bit of animation. So and wanted to branch into more web application development. It’s also a good excuse to remind myself of programming practices without relying 100% on Swift–a language I’m still learning and is a few degrees more complex, versus doing it with Javascript–a language I’m more comfortable with.

I was cruising along fine with my skills map. A large proportion of the first few lessons centers around Codecademy’s online Javascript track. When I finished it up, FreeCodeCamp introduces the concept of Paired Programming and Bonfires. I decided to look into a couple of the the Bonfires on my own. The first three were pretty standard challenges. In fact, #1 and #2 weren’t actual challenges. #3 took a tiny bit of research and I had encountered it before while learning C++. Then I hit the fourth, where it tells you to Factorialize a Number. It was a great exercise that made me think outside of my comfort zone. After trying some really sloppy loops, I ended up with a recursive function.

I’m going to show both of my approaches to this one, first with the recursive function and second using a for loop. I’ve seen both approaches, and I’m by no means an expert at this. I just want to store my attempts at these challenges and walk through them to gain a better understanding. And if it helps someone else understand it too, then great!

Let’s Factorialize a Number

The first thing I had to establish was what factorializing a number is actually about. The explanation was clear cut enough, but being a math dummy, I had to question myself every time I looked at it. And it was as simple as it seems. In laymans terms, when you factorialize a number, you are multiplying that number by each consecutive number minus one. So for example, if your number was 3. You would have something like this:

3! = 3 * 2 * 1

There’s a pretty easy pattern for this:

0! = 1
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1

And on and on, so by the time you reach, let’s say, 9 for example, you might have this:

9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

Factorials are expressed in shorthand as x!, so when you see a number or value with an exclamation mark, you should know that we’re looking at factorials. Now that we kind of understand how that works, we can try to express that in code.

Breaking It Down With a Math Dummy

I said it before, and it needs to be said again. I am bad at math. Terrible at it. I don’t know if it’s because of the way math was taught to me, or what. But me and math don’t go well together. However, even if you are as terrible at math as I am, this one is solvable! So here’s how I broke it down. The Bonfire on FreeCodeCamp starts you off with this:

function factorialize(num) {
  return num;
}

factorialize(5);

Right off the bat, you know they want you to factorialize 5. They also want this written inside of a function called “factorialize”. That’s stuff we already know. So here’s what I was thinking…

1. Since we are essentially looking at determining what num is and then multiplying it by each consecutive number minus one, that can expressed like this num(-1). We need to stop it when num is equal to 1 because going further means hitting 0.

2. In factorials, 0! is always 1. Because multiplying by 0 will frequently return 0, we need to have an exception to prevent that from occurring when the function runs. So we probably need an if conditional statement that checks for 0 and returns 1. Since the conditional will check for and weed out 0, anyway, it might prevent num(-1) from ever getting there.

3. I’ll weed out 0 with the if conditional first. Then deal with num(-1) in a recursive function–which is kind of a hairy exercise for people might be completely new to coding.

Writing Out the Code

Let’s start by doing Step 1 under the break down above. I’m going to weed out the incidence of hitting 0 using an if conditional.

function factorialize(num) {
  if (num === 0) {
         return 1;
      }
}

That was the easy part. What this does is evaluate num. If it detects num is equal to 0 at any point, it will run the statement inside of the if conditional and return 1. Dealing with the recursive function next is where it gets tricky. Though the code is minimal, sometimes the most minimalist of things are the most complicated.

function factorialize(num) {
  if (num === 0) {
         return 1;
      }
   return num * factorailize(num-1);
}

Oh boy, recursive functions. This is something I see in Swift and it always makes me go cross-eyed. Recursive functions run inside of themselves. So you might run a non-recursive function and it spits out a return value and you move on with your life. If you run a recursive function, it spits out a value that gets run again within the function, spits out another value which then gets run again in the function, spits out another and gets run again…on and on until it exits the recursion.

It’s hard to visualize this for me, but the best way is to remember sixth grade math and the order of operations (which, funny enough, is a core component of programming). Within the hallowed rule book of order of operations, you would perform the calculations inside of the parenthesis first. So if you had a formula like this:

(5 * 6) + 9 = n

You would do 5 * 6 first, then take the value you got from that and add 9 to get n. A similar thing is happening with our code. We are first taking num, subtracting 1, then using that value to multiply by num.

So if you had num set to 5, we would be returning this on factorialize()’s first pass:

5 * (5-1)

Second pass:

5 * (4-1)

Third pass:

5 * (3-1)

Fourth pass:

5 * (2 -1)

Fifth pass:

5 * (1-1)
return 1
5 * 1

During the fifth and final pass, our function falls into the if conditional. It returns 1 which num will multiply itself with and the function will exit with a total value.

In the case of factorialize(5). You should get 120. So, the final code all written out:

function factorialize(num) {
  if (num === 0) {
  return 1;
}
     return num * factorialize(num-1);
}

factorialize(5);

We pass a parameter of 5 to factorialize(). It takes it into the function as num and checks if num is equal to 0. If num is equal to 0 it returns 1 and factorializes it as 5(1), where it will stop the recursion. If it’s not 0, it takes num and multiplies it by whatever num-1 is and continues to perform this action until num is equal to 0. The final return is the factorialization of the number 5 that we passed into factorialize(). That number should be 120.

The For Loop Alternative

A for loop will also work as a solution to this Bonfire. There might be other solutions too, because a lot of problems in code can be solved multiple ways depending on style, approach and preferences. I just don’t know of any others. I had actually written a for loop that validates on Free Code Camp and technically does the same thing. I’ve seen others use this approach as well. Though it’s quite a bit more legwork. Here it is:

function factorialize(num) {
  
  for (var i = num - 1; i >= 1; i--)
    num *= i;
  if (num === 0) {
    return 1;
  } else {
    return num;
    }
}

factorialize(5);

Above, we have a for loop within factorialize() that will continue to run so long as i remains greater than or equal to 1. In the above for loop, we make i equal to num -1. Then check if i is still greater than or equal to 1. If it is, then subtract 1 from i, and run the block of code. Within the block, we take num and multiply it by whatever i is. Then we return the result, which in this case should be 120.

More recently (or I could have just overlooked it), FreeCodeCamp added a check for 0 (thus foiling my plans) so I added an if conditional to check for 0 and return 1 if num === 0 ever evaluates to true. Thanks go out to Lena for bringing this to my attention in the comments.

I have a feeling there’s a more elegant way to express this in the For Loop so if you have alternatives or suggestions let me know!

Resources

Bonfire: Factorialize a Number – luishendrix92
One of the more amusing explanations of what a recursive function is. This approach is pretty close to what I got, but it features a check for 1 as well as 0. I’m not sure if you really need that check for 1 and if I’m missing out on anything by not checking for 1 in my own solution. Or it could be another case of different approaches, different styles.



Like the Iron Ion Facebook Page

After a little over two years, I finally got around to setting up an Iron Ion Facebook page for Iron Ion. It wasn’t complicated, difficult or very spectacular. I’m just amazed by how long it took me to get around to it. I don’t even have a good excuse, it was just like saying to yourself, “Geez, when was the last time I went through the spice cabinet to throw out all those spices?” And then you meant to go do it later when you had some time, but forgot because something exciting got in the way.

The Iron Ion Facebook Page

So if you like me on FB: Like Me on Facebook <3

You’ll make me feel a little better about myself. It may even motivate me to organize my spice cabinet because I don’t know how old that cumin is, but I’m very leery of using it. I’ll be posting links mostly, and updates for new posts. Most of them related to an up and coming series of Bonfires from Free Code Camp.

Admittedly, I’m not hip on the social media side of things. Or social marketing, at some point, maybe I’ll get up the nerve to post something funny. Long story short, if you like the page, it’ll only help.

I might also draw an amusing image of a cyberpunk, spandex-wearing, rocket-propelled octopus who codes or something. If time ever permits.



Coding a 1 to 6 Column Layout in HTML & CSS

One of the consistent things I notice while teaching web is that a lot of students understandably have a hard time lining up columns, setting up to create columns and understanding the box model and how it relates to positioning columns in HTML and CSS. Since this seems to be a pretty common hurdle for students I encounter, I think it’s safe to say that a lot of people just learning HTML and CSS for the first time find the topic of creating a 1 to 6 column layout to be challenging and confusing too. I also haven’t seen much in the way of online courses for beginners that really digs into using columns, so here’s my take on it.

The Premise

This is going to be a straight up no responsive code tutorial that will assume your layout has 960px of width to work with. This means we’re not worried about how the columns will scale or how they’ll look on a tablet or a phone. I’m only focusing on fixed widths there to keep things simple. Here’s some basic knowledge you should have first:

  • How to set up an HTML document and connect a CSS Stylesheet to it.
  • An understanding of <div> tags and some other basic HTML tags such as <p>, <a>, <strong>, <em>, etc.
  • A basic understanding of CSS and how CSS Rules are written (ex. the difference between declaring a class or ID selector).

Even if you’re missing some of the stuff in the above list, don’t worry. I’ll try to cover as much as I can as we go along. At this stage, you should also have a code editor that you prefer to use. I tend to recommend either Brackets or Sublime Text for HTML and CSS.

The Box Model and Thinking in Rows & Columns

The Box Model is the basic diagram of how browsers interpret elements on a typical website. It also tells you, the coder, how various components of an element can be manipulated. This is the box model:

boxmodel

The element or grey box on the inside represents your content, in other words, your text, images and anything else you place on the screen is considered to be the element. Just outside of the element, the padding wraps around it. Padding moves the element away from the edges of the box container. Outside of padding is border, it resides between padding and the outermost box model component, border is typically used to–well, create a border around your element and its padding. Finally, on the outside is margin. Margin is used to nudge elements away from each other. Every time you have to move one element around the screen, you are probably going to want to use Margin. Margins are also what we’re, incidentally, going to be using to create our columns today.

I want you to take a look at this next diagram which illustrates how columns and rows are laid out, this diagram goes up to 4 columns, but you can pretty much extrapolate, 5, 6, 7, 8, etc. column layouts from this:

columnrowdiagramRows go down, columns go across. Easy. The spacing in between each box in the above diagram represents margins. Before we get to writing our code, remember that when we want to space elements away from other elements, or move elements around on the screen, we tend to use margins.

Setting Up the HTML File

Below, I have a bare bones HTML file with a bunch of dummy text that we’re going to use for our layout. We’ll be building all our columns on the same page to also give you some practice using floats. Fun, huh? I’ve outputted an HTML page for you to download here: Columns Demo Dropbox (HTML/CSS)

Or you can just copy and paste these into your code editor, this is your HTML page to start:

There shouldn’t be anything too surprising to you at this point. We have a basic HTML document set up, within the head tags, I have declared a title for this page and used to associate our HTML document with our Stylesheet. style.css will power how our columns will be laid out, it is sitting in a folder called /css. Within the rest of the HTML, I have a bunch of comments to tell you where we’re going to start dealing with certain columns, and under each comment is dummy text set inside of tags. All the elements that are visible are wrapped inside of .main. It is always a good idea to wrap your site inside of a container such as .main so you have a consistent basis to declare widths, margins, padding, and border. Typically this containing element has the general width of your website, everything falling inside of it therefore takes the containing element’s width and basis their own widths, margins, padding and borders on it. This should become more evident as we work through the demo. This is your CSS document to start, place your CSS document into a folder called /css:

In our CSS file, we’re importing Droid Serif from Google Web Fonts on Line 3, and setting up basic styling for the body and .main elements from Line 5 – 16. If some of that seems unfamiliar to you, don’t stress about it. This is about columns, and those elements and properties are just there to make our file look a little nicer so we aren’t staring at an unformatted document. If you’re going to be re-using this demo for one of your projects, I suggest removing my styling from Line 1 – 16 so you start off with a blank slate.

Go ahead and open up your HTML file in a browser and take a look at it. Our masterpiece should resemble something like this:

See the Pen EjOwYb by Khanh (@ironion) on CodePen.

OK, let’s make our first column happen.

The One Column Layout

We’ll start off easy. Let’s assume you have a one column layout. We’re going to go into our HTML first, and write in a <div> for our first column. On Line 12 of your HTML document, append the code that is there with the following:

<div class="column-1">
<p>Sleep on keyboard. Poop in litter box, scratch the walls cough furball. Sleep on dog bed, force dog to sleep on floor pelt around the house and up and down stairs chasing phantoms poop on grasses and love to play with owner's hair tie so lounge in doorway. Kick up litter chase laser meow all night having their mate disturbing sleeping humans and mark territory.</p>
</div>

Make sure you leave the comment on Line 11 alone, all we’re doing here is wrapping our paragraph in a <div> and declared a class of .column-1 to it. Once you’ve done this, head into your style.css document and under the comment /* One Column */, declare the following CSS Rule:

.column-1 {
  width: 960px;
  background-color: #b3c8cd;
}

So nothing should be shocking you at the moment, we’ve set our single column to be the same width as our .main container. Therefore, we can see, when we preview the page, that our first div will stretch from one side of the .main container to the other side. Now, we’re going to want to modify this a little bit, because the vast majority of the time, you don’t want your content to be touching the edges of your containing <div>. Let’s amend the CSS code for .column-1 a little, to make it look like this:

.column-1 {
  width: 960px;
  background-color: #b3c8cd;
  padding: 20px;
}

Take a look at your page in a browser now, you’re going to notice that our box, which fit so neatly into .main before, now falls outside of it, the instant we added padding:

Adding padding: 20px broke .column-1 out of .main.

Adding padding: 20px broke .column-1 out of .main.

Think back to the box model for a bit, remember that padding is used to move content away from the edges of a container. When we added padding to our .column-1 element, we’re actually adding 20px to the left, right, top and bottom of the container. That means we actually added 40px worth of spacing to our element which was already 960px. So, to resolve the issue with our padding screwing up our element, we need to remove the 40px we used for padding from .column-1’s total width of 960px. Doing so will give us this CSS:

.column-1 {
  width: 920px;
  background-color: #b3c8cd;
  padding: 20px;
}

And .column-1 will fall neatly back into .main:

If you add padding or border to your container, you will need to make room for it by subtracting from the total width it's supposed to take up.

If you add padding or border to your container, you will need to make room for it by subtracting from the total width it’s supposed to take up.

So, you might be wondering, “If I added a border to my element, do I also have to account for that border in the total width? Yes, you do. Let’s say you added a 5px border around your content. That means you need to remove 10px from your total width and will end up with 910px of total width if you want your container to fall within .main. Heck, let’s do that right now:

.column-1 {
  width: 910px;
  background-color: #b3c8cd;
  padding: 20px;
  border: 5px solid #557f84;
}

Check it out and see how we removed 10px (5px for left and right sides of the container) and our element still falls well within our .main container. Let’s move on to creating a simple two column layout now.

The Two Column Layout

In your HTML document, and under the Two Column Layout comment, append the code with this:

  <div class="column-2-left">
            <p>Sleep on keyboard. Poop in litter box, scratch the walls cough furball. Sleep on dog bed, force dog to sleep on floor pelt around the house and up and down stairs chasing phantoms poop on grasses and love to play with owner's hair tie so lounge in doorway. Kick up litter chase laser meow all night having their mate disturbing sleeping humans and mark territory.</p>
  </div>
  <div class="column-2-right">
            <p>Get video posted to internet for chasing red dot mew but jump off balcony, onto stranger's head. Meow spread kitty litter all over house and plan steps for world domination yet favor packaging over toy, spot something, big eyes, big eyes, crouch, shake butt, prepare to pounce then cats take over the world hate dog. Chew iPad power cord if it fits.</p>
  </div>

We’re declaring two divs and wrapping our two paragraphs with them. The first div wraps the first paragraph and we gave it a class of .column-2-left. The second div we gave a class of .column-2-right. The first paragraph now contained inside of .column-2-left will be sitting on the left side of the .main container, and the second paragraph inside of .column-2-right will be sitting on the right side of the .main container. The Logical Order of Things Now, it’s pretty obvious to some, but it needs to be mentioned that you should set up your HTML elements to contain content in a logical order. Typically that means in the order that you would normally read a page out of a book, from left to right, top to bottom. That means that if you had two paragraphs you want to display inside of columns, that the first one should be set on the left because people are likely to read that one first, and the second paragraph should be set on the right because most people are going to read it second. With that having been said, let’s dive into style.css. Add this code under the Two Column comment in style.css:

.column-2-left {
  width: 430px;
  background-color: #e0ddcd;
  padding: 20px;
  border: 5px solid #938d6d;
}

.column-2-right {
  width: 430px;
  background-color: #e0ddcd;
  padding: 20px;
  border: 5px solid #938d6d;
}

When you preview that in a browser, it’s going to look something like this:

Two columns stacked on top of each other.

Two columns stacked on top of each other.

Those two columns are stacked one on top of the other, which is probably not what you’re looking for. The reason why this is happening is because of the concept of Block and Inline elements in HTML. Block elements can be considered as elements that take up the entire width of a container. These elements will always try to stack versus flow. Inline elements will flow with the text and content that you place on the page. Block elements, such as <div>, <h1>, etc. will not automatically sit side-by-side, even when you’ve created enough space for them to do so. You need to manually tell them to sit side-by-side by using one of several techniques. The most commonly seen is the CSS property: float. Float takes four values: left, right, none, and inherit. We’re mostly concerned with float: left and float: right today, as these will allow us to position our columns side-by-side instead of the mess you see in the image above. I want you to apply floats to .column-2-left and .column-2-right:

.column-2-left {
  width: 430px;
  background-color: #e0ddcd;
  padding: 20px;
  border: 5px solid #938d6d;
  float: left;
}

.column-2-right {
  width: 430px;
  background-color: #e0ddcd;
  padding: 20px;
  border: 5px solid #938d6d;
  float: right;
}

Check out our layout in a browser now and you should be seeing something like this:

Much better.

Much better.

Sometimes what you see above will work perfectly fine for you, sometimes, you want a bit of margin in between those two containers so they’re not touching each other. I’m going to apply a 20px margin between the above containers. Remember, every time we add margin, border, or padding to a container, we have to take away from its width. Otherwise, it’ll fall outside of its container. So, since we want 20px of space between .column-2-left and .column-2-right, I need to subtract 10px of width from both of them, then declare margin-right: 10px on .column-2-left and margin-left: 10px on .column-2-right. Just like this:

.column-2-left {
 width: 420px;
 background-color: #e0ddcd;
 padding: 20px;
 border: 5px solid #938d6d;
 float: left;
 margin-right: 10px;
 }
.column-2-right {
 width: 420px;
 background-color: #e0ddcd;
 padding: 20px;
 border: 5px solid #938d6d;
 float: right;
 margin-left: 10px;
 }

Notice I removed 10px from the width on both of the columns to account for the margin we just added? You should see something like this now:

I trimmed some of the body copy to keep my columns a little neater. Feel free to remove or add copy as needed if you're crazy about keeping things the same relative size like I am.

Looking good.

Let’s create a three column layout now!

The Three Column Layout

Let’s tackle our three column layout now. You should be somewhat familiar with the drill, let’s append our HTML and add in our <div> tags for our columns. One for each paragraph, first paragraph is left, second is in the middle and third is going to be on the right. Under the Three Column Layout comment change what is there with this:

<div class="column-3-left">
            <p>Sleep on keyboard. Sleep on dog bed, force dog to sleep on floor pelt around the house and up and down stairs chasing phantoms poop on grasses and love to play with owner's hair tie so lounge in doorway. Kick up litter chase laser.</p>
  </div>
            
  <div class="column-3-middle">
            <p>Get video posted to internet for chasing red dot mew but jump off balcony, onto stranger's head. Meow spread kitty litter all over house and plan steps for world domination yet favor packaging over toy, spot something, big eyes.</p>
  </div>
            
  <div class="column-3-right">
            <p>Shake treat bag stand in front of the computer screen mew play riveting piece on synthesizer keyboard intently sniff hand rub face on everything meowing non stop for food. Destroy the blinds. Parts with tongue then lick owner's face.</p>
  </div>

Diving into our CSS now, add this code under the Three Column comment:

.column-3-left {
  width: 270px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
}

.column-3-middle {
  width: 270px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
}

.column-3-right {
  width: 270px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: right;
}

In the above code, we’re floating the left and middle columns to the left, and the last column to the right. Despite what most would assume, there is no such thing as float: middle. Which means dealing with columns in the middle will have to be settled with margins while using either float: left or float: right. Let’s add in our margins, but let’s think about it a little first. We want 20px of spacing between each column. That means, that .column-3-left is going to declare margin-right: 10px, and .column-3-right is going to declare margin-left: 10px. That leaves .column-3-middle which will need to declare margin-left: 10px and margin-right: 10px in order to cover the space on both sides of it. Also, don’t forget to remove the appropriate width from each of your columns when you’re declaring a margin between them:

.column-3-left {
  width: 256.65px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
  margin-right: 10px;
}

.column-3-middle {
  width: 256.65px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

.column-3-right {
  width: 256.65px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
  margin-left: 10px;
}

Yes, you’re looking at a decimal pixel set of columns up there (also called a floating value pixel) so that all three will fill the width for a .main with 960px of width. That’s how the more precise math breaks down for this particular layout. Now, this is what works if we were really concerned with having the exact same width for each column in a fixed width layout. Half-pixels or floating value pixel can be problematic because they can sometimes cause unintended results, usually while working with images, printing and some tranformations in CSS. So, let’s try to adjust our values a little to avoid the use of the floating value pixels. Normally what I would do is one of three things: 1) Remove the floating value pixels and allow the extra pixels in spacing in the margin 2) apply the full pixels to the left and right columns, 3) add two full pixels to the center column, like this:

.column-3-left {
  width: 256px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
  margin-right: 10px;
}

.column-3-middle {
  width: 258px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

.column-3-right {
  width: 256px;
  background-color: #d5edcd;
  padding: 20px;
  border: 5px solid #67a155;
  float: left;
  margin-left: 10px;
}

It’s not too noticeable to the vast majority of users that the center column is two pixels wider than the left and right columns and you avoid using a decimal value for your pixel widths–if that was a concern. Should you be worried about floating value pixels? For a fixed width layout, that all depends considering that a fixed width layout will always force you to either round up your pixels or settle for the floating value pixels so it becomes a question of how precise you want to be, or if you can settle for knowing your columns may have varying widths by a couple of pixels in certain circumstances, if you need precisely the same width columns and don’t want to use floating value pixels, allow for the spacing in your margins. For responsive layouts you are likely to be using more precise values and can allow the browser to automatically calculate values for you using the calc() function in CSS. So for now, don’t stress too much about using decimal values vs. evening out the values. All right, that’s enough of that. Let’s move on to our four column layout now.

The Four Column Layout

You should know the drill now, this time we have two middle columns, one left and one right. The second and third paragraph under the Four Column Layout comment should be wrapped using a <div> with the same class of .column-4-middle. So under the comment Four Column Layout, add this:

  <div class="column-4-left">
            <p>Sleep on keyboard. Poop in litter box, scratch the walls cough furball. Sleep on dog bed, force dog to sleep on floor pelt around the house and up and down stairs chasing phantoms poop on grasses and love to play with owner's hair tie so lounge in doorway.</p>
  </div>
  
  <div class="column-4-middle">
            <p>Get video posted to internet for chasing red dot mew but jump off balcony, onto stranger's head. Meow spread house and plan steps for world domination yet favor packaging over toy, big eyes, crouch, shake butt. Chew iPad power cord if it fits.</p>
  </div>
            
    <div class="column-4-middle">
            <p>Shake treat bag stand in front of the computer screen mew play riveting piece on synthesizer keyboard intently sniff hand rub face on everything meowing non stop for food. Destroy the blinds. Make meme, make cute face then lick owner's face.</p>
  </div>
            
  <div class="column-4-right">
            <p>Leave dead animals as gifts play time, or scamper, sweet beast. Why must they do that cat snacks damn that dog leave dead animals as gifts sleep nap so stretch. Roll on the floor purring your whiskers off paw at your fat belly. Put toy mouse in food bowl.</p>
  </div>

We’re reusing the column-4-middle class for the second and third paragraphs. This is because I anticipate those two will have pretty much the exact same styling and width values. So it doesn’t make sense to declare a different class for each because that would be extra work to style two classes in exactly the same way versus if we just reused the one class to save ourselves some. Going into our CSS, here’s what we’re going to end up with:

.column-4-left {
  width: 175px;
  background-color: #f5d7ce;
  padding: 20px;
  border: 5px solid #cb785e;
  float: left;
  margin-right: 10px;
}

.column-4-middle {
  width: 175px;
  background-color: #f5d7ce;
  padding: 20px;
  border: 5px solid #cb785e;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

.column-4-right {
  width: 175px;
  background-color: #f5d7ce;
  padding: 20px;
  border: 5px solid #cb785e;
  float: right;
  margin-left: 10px;
}

Three CSS Rules to style four columns is a bargain. Outside of that, there’s nothing very surprising here so long as we got our one, two and three column layouts working out, the four column version won’t have any curve balls for us. The only thing to note is the re-use of the middle column CSS Rule to save on time and code we have to write. Let’s head on over and deal with five columns now.

The Five Column Layout

All right, moving things a long a little faster, here’s our HTML. Again, we’re going to be reusing the column-5-middle class because all of those should have the same styling and widths, therefore, no reason to write a different class for each:

  <div class="column-5-left">
            <p>Kick up litter chase laser meow all night having their friend disturbing the sleeping humans and mark this territory.</p>
  </div>
            
  <div class="column-5-middle">
            <p>World domination yet favor packaging over toy, spot something, big eyes, big eyes, purr, crouch, shake butt.</p>
  </div>
            
  <div class="column-5-middle">
            <p>Rub face on everything meowing non stop for food. Destroy the blinds. Make meme, make cute face then lick owner's face.</p>
    </div>
  
    <div class="column-5-middle">
            <p>Rub face on everything meowing non stop for food. Destroy the blinds. Swish tail, pounce and roll then lick owner's face.</p>
    </div>
            
  <div class="column-5-right">
            <p>Why must they do that cat snacks sleep nap so stretch. Mark territory. Chase mice. Roll on the floor purring your whiskers off paw.</p>
  </div>

Here’s our CSS. Nothing surprising again, we’re just setting up more columns now and adjusting the values of our widths to account for padding, border and our margins:

.column-5-left {
  width: 126px;
  background-color: #e7e6f8;
  padding: 20px;
  border: 5px solid #c2beeb;
  float: left;
  margin-right: 10px;
}

.column-5-middle {
  width: 126px;
  background-color: #e7e6f8;
  padding: 20px;
  border: 5px solid #c2beeb;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

.column-5-right {
    width: 126px;
  background-color: #e7e6f8;
  padding: 20px;
  border: 5px solid #c2beeb;
  float: right;
  margin-left: 10px;
}

The bottom of your document should look something like this now:

Three, four and five column layout.

Three, four and five column layout.

Now, the six column layout should be a snap at this point. Or at least you should be able to suss it out for yourself. Go ahead and try it out on your own before moving onto the answer below. If it worked, great!

The Six Column Layout

Most of the layouts I’ve encountered don’t go further than six columns, but you never know when you might encounter a seven, eight, nine, ten, etc. column design. The principles we’ve gone over in this tutorial would work for all of them. Just remember to adjust your values based on how much width you have, use your floats, and never write more classes than absolutely necessary. Here’s our HTML for the six column layout:

  <div class="column-6-left">
    <p>Chasing phantoms and love to play with owner's hair.</p>
  </div>

  <div class="column-6-middle">
    <p>World domination yet favor packaging over toy.</p>
  </div>

  <div class="column-6-middle">
    <p>Rub face on everything meowing for food all the time.</p>
  </div>

  <div class="column-6-middle">
    <p>Purr and roll around batting toy. Destroy the blinds.</p>
  </div>

  <div class="column-6-middle">
    <p>Make meme, make cute face bathe self then lick owner.</p>
  </div>

  <div class="column-6-right">
    <p>Why must they do that cat snacks sleep nap so stretch.</p>
  </div>

And here’s our CSS:

.column-6-left {
  width: 94px;
  background-color: #d7ede9;
  padding: 20px;
  border: 5px solid #5e9d92;
  float: left;
  margin-right: 10px;
}

.column-6-middle {
  width: 93px;
  background-color: #d7ede9;
  padding: 20px;
  border: 5px solid #5e9d92;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

.column-6-right {
  width: 94px;
  background-color: #d7ede9;
  padding: 20px;
  border: 5px solid #5e9d92;
  float: right;
  margin-left: 10px;
}

Note I allowed for additional width on my left and right column. Just to demonstrate that you can allow for additional spacing between margins in order to void floating value pixels:

.column-6-left {
  width: 93px;
  background-color: #d7ede9;
  padding: 20px;
  border: 5px solid #5e9d92;
  float: left;
  margin-right: 11px;
}

.column-6-middle {
  width: 93px;
  background-color: #d7ede9;
  padding: 20px;
  border: 5px solid #5e9d92;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

.column-6-right {
  width: 93px;
  background-color: #d7ede9;
  padding: 20px;
  border: 5px solid #5e9d92;
  float: right;
  margin-left: 11px;
}

All in all, we should have something that looks like this when we’re all done: See the Pen VLVMZE by Khanh (@ironion) on CodePen.

Here’s our finalized HTML:

And our finalized CSS:

If you’d like to download the completed version of this demo here you go: Columns Demo Finished (HTML/CSS)

A Note About Clearing Your Floats

Also keep in mind that our layout doesn’t take into consideration the need to clear your floats when you use them. Clearing occurs after floating as it allows you to remove the float property from subsequent elements that may not need it. Failing to clear floats will cause elements following your floated elements to attempt to sit themselves in the rift of space created by your float properties. To declare a clear, you call the CSS clear property with a value of both. Like this:

.footer {
clear: both;
}

In the above code, your clear: both; declaration will effectively tell the element with a class of .footer to clear and disregard all the floats you declared on the elements that preceded it. In days gone by (read: a couple of years ago), people still created elements specifically geared towards clearing. Nowadays, may coders clear the element following the float if they don’t need the float to affect it.

Hooray! We’re done with our layout, now you should have six rows, each with a varying amount of columns that fall neatly into a 960px width total container. There are column generators and other generation resources you could use for this, but it’s better to learn by writing things from scratch before we resort to automation. With CSS3 out, there are some alternative and neat ways to create columns too, such as using the CSS column property, which I’ll cover in another tutorial. With that having been said, I’ve linked to an older generator that still deals with fixed width columns and another site that will detail how floating and clearing works for positioning elements and more.

Resources

Page Column Generator
Shaye Howe, Positioning Content



Understanding & Using WP Query

WP Query

In order to adequately develop a fully functioning WordPress (WP) theme, you need to know WP Query and understand how it works, why it’s necessary, when you need to use it and where it should be placed. WP Query is a class with a host of powerful functions (called template tags in WordPress) that allow you to call up the WP database and have it return the data that you need. Knowing that, you can use WP Query to do things such as display specific posts, categories, images and even use it in conjunction with custom post types to get at the specific data that you need for your WP theme or plugin project.

What You Need to Have and Know

I’m not going to go into too much detail about what programming is, but I will try my best to elaborate on some of the concepts for those who might not be familiar with it. This tutorial will assume that you posess:

  • Knowledge of HTML (intermediate)
  • A passing understanding of PHP is helpful
  • A basic understanding of WordPress’ file structure
  • How to set up a bare bones WordPress instance on your localhost (see here for help)

Before you go on with the tutorial, set up a new instance of WordPress on your localhost, you don’t need to install any themes, plugins or special extensions. I am going to use the base TwentyFifteen theme that comes with vanilla WordPress for this tutorial and that should be all that you’ll need too. If you need help installing WordPress on your localhost, head here if you run Windows and here if you run OSX (skillcrush.com).

Because PHP needs to interact on a server level with the database, you must run a local server environment or run a live server environment for any of the demo code in this tutorial to work. I highly recommend setting up a local server environment either using XAMPP or MAMP as working on a live server is much less efficient.

A Crash Course in OOP

WP_Query is a Class that exists within WordPress. It was (like the majority of the WordPress core software) written in PHP. PHP is an Object Oriented Programming language that allows you to write code that interacts with a database. In WordPress’ case, that is typically a MySQL database. This database stores a lot of information for WordPress websites, including user information, all posts, image paths and more.

What’s a Class?

In Object Oriented Programming (typically shortened to OOP), a class can be simply described as a bunch of functions and variables grouped together. A variable is a container for data, a function is code that is written to perform a task and can be reused over and over again. Inside of a Class, Functions are called Methods and Variables are called Properties.

Now, within WP_Query there are a ton of functions that have been pre-written by the WP Developers. These functions are called Template Tags (instead of Methods). Each Template Tag does something specific. For example the get_the_title() template tag will retrieve the title for a post or page.

Many Template Tags (much like Methods) take parameters, which are values that you can feed the Template Tag in order to get specific kinds of information. Most of the time, when you use a WP_Query, you’re looking for more than just one piece of information. Which frequently requires you to put in multiple parameters by loading them up into an array, but we’ll get to that soon.

The final thing we should probably be familiar with is the semicolon that ends all PHP statements. Missing a semicolon can cause all of our code to break so it’s important to watch out for them.

What’s a Query?

A Query, in programming, is the act of asking the database to retrieve and return information to us. This information can be anything from the first names of all our users, to the post titles of all the posts in a specific category. How you write your query and what you ask for will determine what you get back from the database.

In WP’s case, all of its Template Tags were written to query the database for specific pieces of information. And there are a lot of them if you look at the WP Codex for WP_Query: WP Query Documentation (WordPress.com)

So What is WP_Query Exactly?

Putting together what we learned about Classes and Queries, we can presume that WP_Query is a Class with a lot of Template Tags, those Template Tags all perform functions that query the MySQL database and return pieces of information to us depending upon the Template Tag that we used.

Ugh, Why do I Need to Know WP_Query?

Coming from an HTML/CSS only background and having to stare WP_Query down is intimidating. But you need to know WP_Query if you want to get serious about WordPress Theme development, plugin development, and sometimes even when you’re just modding existing themes. WP_Query allows you to do useful things like display posts within specific categories or write in restrictions for certain user groups, etc.

Your First Ultra Simple WP_Query

Let’s load up our instance of WordPress, I’ve created a basic page template for us to fuss around with WP_Query that includes the header and footer calls for WordPress as well as the essential HTML structure. Outside of the basic setup, there should be nothing else on the page. You can copy and paste the basic template code below, or download it here: Download page-queries.php (PHP)

Once you download the page template, put it into the root folder of your TwentyFifteen theme folder, then create a new page using the WP Query Page template and give it a title (I named mine, “Query Page”) and load up the page on the frontend of your WordPress Instance. You should be looking at something that looks like this:

Good to go!

Good to go!

OK, let’s write our very first WP_Query. This is a really simple one that I mentioned above, it’s get_the_title() which will be used to query our Database and return the title of the page that we’re on. The title you get back should be the title you entered for your page. Type this in between your <header></header> tags, if you downloaded my file you should place this on Line 14:

<?php echo get_the_title(); ?>

Save your file, and refresh the page in your WordPress instance. You should now see this:

You just wrote a super simple query!

You just wrote a super simple query!

If you see the title of your page displayed, congratulations! You’ve just written a super simple query that went into the database, grabbed the title of the page and returned it to you on the page. Let’s go over what exactly we wrote up there. Chances are pretty good that this isn’t the first Template Tag you’ve encountered or even used as you worked with WordPress, but bear with me. PHP is said to be written in blocks. A PHP block begins when you open the block with this <?php and the block ends when you close it with this ?>. Within a PHP block, you may have pure PHP code or a mixture of PHP and HTML. In the above code, we use echo which is our way of telling PHP to display something we tell it to display. In this case, we’re telling PHP to display whatever the value of get_the_title() is. get_the_title() is a WordPress Template Tag (also known as a Method). This Template Tag retrieves the title of the post or page that it was used on. In my case, my page was titled “Query Page”, which is exactly what the Template Tag fetched. As an example of mixing HTML and PHP together, let’s make the title of the page an <h1> like this:

<h1><?php echo get_the_title(); ?></h1>

Notice that I used the <h1> outside of the PHP Block. It is also valid, but less seen, to write it like this:

<?php echo '<h1>' . get_the_title() . '</h1>'; ?>

I prefer to do it the first way wherever possible because it’s faster to type, easier to read (in my opinion) and I’ve personally seen it in use more often in WP development than the second style when we’re trying to style pretty simple and very small PHP Blocks. Both are legitimate styles as far as I know, I just prefer the first and will use it wherever I can. Just so we’re on the same page, the second example does the exact same thing as the first, the only difference is the second one has HTML inside of the PHP Block. When you use HTML inside of a PHP Block, you need to use quotes in order for it to read and display properly. Whenever you have elements in a PHP Block that mix in terms of needing quotes and not needing quotes (in this example, two HTML tags that need quotes and one Template Tag that doesn’t) you have to combine them together in the block by using periods. When we link elements together like this, we are said to be “concatenating” them.

WP_Queries and Arrays

Getting the title of a post or page is fine and dandy, but a lot of the time, you’re going to be using WP_Query in conjunction with arrays to request more than one piece of data from the database. Within PHP, there are three popular forms of arrays: Indexed, Associative and Multidimensional. I’m only going to touch upon the second and third: Associative and Multidimensional, in this tutorial. This is because the majority of the time, you are going to be using Associative or Multidimensional Arrays with WP_Query and if we were to spend time digging into arrays, we’d be here all day. Think of an Associative Array as a collection of keys and their values. A key is an identifier that we associate to a value so we can easily locate the value again. In fact, if you look inside your MySQL database, you’ll notice that many of the pieces of data in it have keys and values associated with those keys. We tend to call this a key value pair (KVP) type of data structure. A Multidimensional Array is an array that holds other arrays. This tutorial focuses on Associative Arrays. An Associative Array in PHP might look something like this, if we were trying to build an array of employees at a company. If you’re interested in testing out arrays, go ahead and plug in this code inside of <div class=”entry-content”>…</div>:

In the above PHP Block, we’re naming our array $employees and defining an array of key and value pairs. The keys would be the employee’s name and the value is the occupation. As proof that we actually created this array and it is, in fact, generating key value pairs, let’s print it out so we can read it. Plug in this appended code:Line 7 is what I’ve freshly added. The echo will output an HTML preformatted tag and its closing pair. Print_r will display the contents of our array. If everything goes well, you should see something like this on your page:

Array
(
    [Brenda] => accountant
    [Jonathan] => graphic designer
    [Aria] => pirate queen
)

Print_r is generally used to debug PHP code. We’re not too worried about formalities with this. So long as you got the above output, you’re good to go. Let’s comment out the above code for the $employees array and do something a little more relevant to WordPress. Within <div class=”entry-content”>…</div>, we’re going to add in a different array. An array we might define for the purposes of WP_Query would look more like this:

What we’re doing in the above PHP Block is telling WordPress that we want to create an array called $my_cakes. Within that array, we define what we want based upon existing keys that WordPress recognizes: tag and category. In this example, we want data that contains the value of ‘cake’ within the tags, and the value ‘recipes’ within the categories. After that, we load our array into a variable that we called $get_cakes. Every time you create a variable to hold content in PHP, you precede it with the dollar sign.

The above code won’t display anything at the moment. What it does do is tell the database to locate data tagged with ‘cake’ and categorized under ‘Recipes’. If we were to add more to the above PHP Block, we could get it to return all the Cake Recipe posts we might have in our blog. I’ve created three dummy posts and tagged them with ‘cake’ and created a category called ‘Recipes’. Go ahead and do the same, then append the above code with the following:

Starting from Line 12 is what was freshly added. What we’re doing now is creating a while loop. A while loop in programming is a chunk of code that will perform an action over and over again when a conditional statement (if statement in this example) evaluates as ‘true’. In this case, we’re telling PHP that we want it to reference the query and display the title of the query for each post that it can find that was tagged as ‘cake’ and categorized as ‘recipes’. Here’s a line-by-line of what’s going on: Line 13: Uses an if statement to determine if our $get_cakes query is returning any posts. In other words, if $get_cakes has found any posts that qualify as being tagged ‘cake’ and categorized as ‘recipes’, then evaluate this if statement as being ‘true’. Line 14: Enters into a while loop that states that while $get_cakes has posts (in other words, while the if statement in Line 13 evaluates as true) to go forward to perform the task that begins on Line 15. Line 15: For each post that we will output, reference the values retrieved by $get_cakes. Line 16: Outputs the title followed by a line break based upon the posts we got from $get_cakes. Line 17 – 18: Begins the else statement that will serve as our fallback in case our if statement cannot find any posts using the $get_cakes query. Line 19 – 20: Outputs the text, “sorry, no posts found.” if $get_cakes is empty, or in other words, cannot find any posts matching the key/value we entered in $my_cakes. Line 23: Restores the original post data by resetting the post variable for the main loop. It is important when we write any custom loops in WP, that we call this function. If all goes well, you should be three posts containing your cake recipes show up under the title of the page on your screen when you refresh the browser. So, we’ve successfully filtered out our cake posts from our recipes category. That might come in handy in some instances where you want a particular page to only output certain posts. A Quick Note About Naming Conventions Now’s as good a time as any to mention how WordPress prefers you name objects. I’m used to the general naming convention of camelCase when it comes to programming. WP, for whatever reason, prefers that developers use underscores instead. This doesn’t mean that if you use camelCase in your WP Development that none of your named objects will work, it’s a perfectly acceptable method and if you find yourself writing vanilla PHP, camelCase is the recognized way to go. The underscores are a preference on WP’s part and while we’re playing in their backyard, it’s best to be polite and follow their rules.

 Multidimensional Arrays & WP Query

OK, that was fun. How, let’s say we want to display posts under multiple categories instead of just one. I’m going to create three new dummy posts and categorize them all under one new category. It doesn’t matter as much what you this new category, I just call mine “Events”, I want you to also categorize these posts under “Recipes”. You can tag them whatever you want, I just tagged mine under the “cake” tag that I already had going. With your three new posts, let’s write a multidimensional array then load it up in our query and output the titles and excerpts of the posts that were categorized under both ‘Events’ and ‘Recipes’ now, you will need to replace the two category ID numbers with numbers corresponding to your categories (to quickly find what numbers you’re using go to Posts > Categories then mouse over the Events and Recipes categories, you should see their ID numbers in the status bar:

What we’re now doing in the above post is using category__and which is a WP Query category specific parameter. It looks for posts that were listed within the specified categories and will only display posts that are categorized under all of them. In this case, unless a post falls under 20 (recipes) and 30 (events), it won’t get displayed.

The other different thing is under our ‘echo the_title()’ we added an ‘echo the_excerpt()’ to display the excerpts of the posts. If all went well, you should see your three new dummy posts with their titles, and underneath in italics, are the excepts.

Custom Posts & WP Query

All right, we’re going to eventually need to use WP Query with custom post type. Custom Post Types are extremely useful because your content doesn’t always neatly fall under a Post or a Page within WordPress. You’ll also need to know WP Query in case you need to filter, or specifically apply something to a Custom Post Type that was used by a plugin. Like, for instance, if you wanted to display only Testimonials that received a 4/5 or better star rating from a Testimonials Plugin.

At this point, we’re going to need a custom post type, you can create one manually. Or, you can download any of the leading Custom Post Type Plugins if you prefer a faster solution. I can recommend Advanced Custom Fields or Types.

On our test site, let’s create a Custom Post Type called “Clients”, don’t worry about fussing with fields, generating the most bare bones custom post type will be perfectly fine for this tutorial. If you can’t be fussed to go through the motions of installing a plugin or figuring out Custom Post Types right now, then add this code into your functions.php file at the bottom:

After you have your custom post type, create two custom posts, I titled mine, “Hannah” and “George”, both of them have a paragraph of dummy text. All right, let’s use our new custom post type (client_post_type) to output Hannah and George along with an excerpt from each of those entries. Here’s what I’m going to plug into query-page.php:

So most of that should be pretty familiar at this point. The only thing to truly note is the post_type parameter that takes in our custom post type referred to as: “client_post_type”. You can perform this WP Query on other custom post types you might encounter as well.

When to Use WP Query

We’ve been using WP Query for pretty light lifting in this tutorial, and you’ll no doubt find more creative ways to leverage the Class. While it can be useful, you should be aware that querying a lot in your theme or plugin isn’t always the best way to go and there’s a lot more to it than meets the eye, despite the length and the content we went through here, we’re only scratching the surface of what WP Query can do. It’s highly recommended that you check out the WordPress Codex: WP Query on WordPress Codex. Also keep using the test site to play around with WP Query to see what else you can come up with and check out some of the resources I’ve linked below for different WP Query writing styles and uses as well as some more information about when, where and how to use it. Enjoy!

Resources

Mastering WP Query on wpmudev
Generate WordPress WP Query
Introduction to WP Query on Elegant Themes
Mastering WP Query, Tuts+
Paul Lund, Create Custom Queries in WordPress



Using CSS Attributes Selectors

A CSS Attribute Selector, in its most simple format looks like this: selector[attribute]

Its purpose is exactly as it sounds, it allows you to select an element based upon its attribute and using css attributes selectors is exactly what we’re talking about today. While you might be wondering how or why that’s useful, given that most attributes within HTML can already be selected by just declaring that attribute, the CSS Attribute Selector can extend your selection abilities as well as allow you to specify precise values and custom attributes. That, and the most basic Attribute Selector indicated above is far from the only one that exists out there. In this tutorial, we’re going to explore the different types of attribute selectors and the interesting and useful implementations for each.

Selector[Attribute]

This attribute selector works with an element selector and is typically expressed inside of square brackets. Usually you use this to select the attribute of the element instead of the assigned value. An example:

HTML:

<p>Warm Kitty, Soft Kitty,</p>
 <p>little ball of fur.</p>
 <p title="kitty">Sleepy Kitty, Happy Kitty,</p>
 <p>purr, purr, purr.</p>

CSS:

p[title] {
 color: #de858a;
 font-style: italic;
 font-weight: 700;
 }

In the above code, we declare a <p> with a title attribute (you can check out other types of attributes available in HTML here: MDN, HTML Attribute Reference). Our title attribute takes “kitty” as its value, but that isn’t relevant yet here. Within our CSS, we target the span attribute using p as our general selector and declare [title] immediately after it. We style, therefore, only the line of text containing <p> with an attribute of title. It should look like this:

See the Pen General Attributes Selector by Khanh (@ironion) on CodePen.

Selector[Attribute=”Value”]

This more specialized attribute selector targets a specific attribute assigned to an element with an equally specific value assigned to the attribute. For example: HTML:

<p>Warm Kitty, Soft Kitty,</p>
    <p>little <a href="#ball">ball of fur</a>.</p>
    <p>Sleepy Kitty, <a href="#happy">Happy Kitty</a>,</p>
    <p>purr, purr, purr.</p>

CSS:

a[href="#ball"] {
  color: #de858a;
  font-weight: 700;
  text-transform: uppercase;
  text-decoration: none;
}

In the code above, we declared an href attribute with a value of #ball (which, in our example, won’t seem to do anything when clicked). In our CSS, we declared a as the element selector and specified [href] as the attribute and go on to further specify that href should have a value of #ball before assigning the styling. Note that there is another <a> with an href attribute in our HTML, but it is unaffected. Check out the attribute selector with value example:

See the Pen Attribute With Value Selector by Khanh (@ironion) on CodePen.

Selector[Attribute^=”Value”]

This attribute selector will locate any attribute beginning with whatever the value is specified as. This is useful for detecting things such as keywords within your copy, links, images, downloads, etc. because it looks for whatever the value is at the send of a string. A string is a statement, sentence, a URL, a series of characters like “Hello, how are you?”, or “http://www.google.com” or “3479 Winding Hollow Way”. Here’s an example of usage:

HTML:

<p>Warm Kitty, Soft Kitty,</p>
<p>little <a href="https://en.wikipedia.org/wiki/Warm_Kitty">ball of fur</a>.</p>
<p>Sleepy Kitty, Happy Kitty,</p>
<p>purr, purr, purr.</p>

CSS:

a[href^="https"]:after {
  font-family: FontAwesome;
  top: 0;
  left: -5px;
  content: " \f0a9";
}

The above code declares an <a> with a link directed to the Warm Kitty Poem Wikipedia page. In the CSS, we are using the caret character to indicate that we want CSS to look for anything with a value of “https” if it appears first in a string of an href attribute. Some of you may recognize caret by its other name, the circumflex. Here’s what this one looks like:

See the Pen Attribute Selector Beginning of String by Khanh (@ironion) on CodePen.

Selector[Attribute$=”Value”]

Here’s a good one that’s very useful for targeting specific file types that happen to be linked or loaded through HTML. I’ve seen this one used a lot to indicate different download types (something I really should write into my own site). The $ tells CSS to look for the value at the end of a string. Here’s its implementation:

HTML:

<p>Warm Kitty, Soft Kitty,</p>
    <p>little <a href="http://www.google.com">ball of fur</a>.</p>
    <p>Sleepy Kitty, Happy Kitty,</p>
    <p><a href="#.pdf">purr, purr, purr.</a></p>

CSS:

a[href$=".pdf"]:after {
  font-family: FontAwesome;
  top: 0;
  left: -5px;
  content: " \f019";
}

Up there, we declared a PDF to be downloaded when someone clicks on the purr, purr, purr portion in HTML. Within our CSS, we target specifically the links that end with .pdf. Notice, when you run it, that it doesn’t detect the link that ends with .jpg. Here it is in action:

See the Pen Attribute Selector End of String by Khanh (@ironion) on CodePen.

 Selector[Attribute*=”Value”]

The use of the asterisk here detects if the value appears anywhere within the attribute. You can use this one whenever you might want to highlight a specific word, link or other element. Like this: HTML:

 <p>Warm Kitty, <span title="great to snuggle">Soft Kitty</span>,</p>
    <p>little <span title="cats are like this">ball of fur</span>.</p>
    <p>Sleepy Kitty, Happy Kitty,</p>
    <p><span title="cats always do this">purr, purr, purr.</span></p>

CSS:

span[title*="cat"] {
  color: #663750;
  font-weight: 700;
  border-bottom: 2px solid #663750;
}

See how only the span titles with an instance of the word “cat” are selected and subsequently affected? Here’s the visual:

See the Pen Attribute Selector Contains A Value by Khanh (@ironion) on CodePen.

There are a couple more attribute selectors that I rarely ever use, but exist within CSS. I’ll go over these now.

Selector[Attribute|=”Value”]

The bar targets attributes that contain the value immediately followed by a dash. For example: cart-port, red-wine, salad-dressing. This might be useful if you have attributes that are required to have dashes in them, such as file names and certain Classes and Methods in some frameworks. Here’s an example of this one: HTML:

<p>Warm Kitty, <span title="great to snuggle">Soft Kitty</span>,</p>
    <p>little <span title="cats are like this">ball of fur</span>.</p>
    <p>Sleepy Kitty, Happy Kitty,</p>
    <p><span title="cats-always do this">purr, purr, purr.</span></p>

CSS:

span[title|="cats"] {
  color: #663750;
  font-weight: 700;
  border-bottom: 2px solid #663750;
}

And here it is in action:

See the Pen Attribute Selector Contains A Value by Khanh (@ironion) on CodePen.

Selector[Attribute~=”Value”]

The tilde will target attributes that contain the value in a list, even if that value appears in a space separated list. Like this:

HTML:

<p>Warm Kitty, <span title="great to always snuggle">Soft Kitty</span>,</p>
    <p>little <span title="cats enjoy this">ball of fur</span>.</p>
    <p>Sleepy Kitty, Happy Kitty,</p>
    <p><span title="cats always do this">purr, purr, purr.</span></p>

CSS:

span[title~="always"] {
  color: #663750;
  font-weight: 700;
  border-bottom: 2px solid #663750;
}

Up there, we have the word ‘always’ appearing in the title attribute in two spans. When we run the code, we see that it searches, locates and highlights those spans with always, regardless of where always is on a list. I have a hard time coming up with a reasonable situation to use this one, but if you have any ideas, feel free to let me know! Here it is in an example:

See the Pen Attribute Selector Contains A Value by Khanh (@ironion) on CodePen.

And there you have it, Attribute Selectors in a nutshell. A lot of the time, many of these selections can be done in Javascript. I’m sure the debate is still out there, but I’m of the opinion that CSS is faster and puts less load on the CPU. So any time I can use CSS to accomplish something of equivalent function instead of JS, I tend to take that route.

Resources

30 CSS Selectors You Must Memorize, TutsPlus
MDN, Attribute Selectors
CSS Tricks, [Attribute]



5 Frameworks Worth Checking Out

Frameworks seem to be the in thing and while I’m still kind of old school about this in that I’ll insist upon building things from scratch, I do still use a framework to avoid the hassle of the setup. It’s also imperative that designer/developers understand at least one major framework because hey, they are tools that exist to speed up your development time and you can’t go into every project setting things up from the ground. I’m only going to go over the lesser known frameworks here because knowing jQuery, Bootstrap, Foundation, AngularJS, etc. are pretty much a given. Here are some of the frameworks I’ve been using lately.

Material Design Lite
Gorgeous, well thought out, logical and the documentation is available right on the site along with helpful examples and visual demos. Material Design is a beautiful thing and this framework makes working with it super simple.

Bootply
I prefer Foundation over Bootstrap 9 out of 10 times, but when I do use Bootstrap for a client, I head off to Bootply first. It’s always a good idea to know how the guts of a framework is setup, and once you have that down, using a generator like Bootply will speed up your development time exponentially. Beautifully written and easy to use.

Webix – DataTable
If you ever find yourself having to work with a good amount data, Webix Framework’s DataTable is a treat. Working with tables and tons of data can get frustrating, tedious and downright painful. This takes a little bit of the edge off. Webix has a lot of components as a part of its framework, but the DataTable is by far my favorite.

CakePHP
Code generation and scaffolding for PHP? Gorgeous! This makes writing web apps that have to deal with PHP a snap. And as much as I advocate building PHP from scratch, I will admit it’s a chore unless you have a good framework to smooth things out. I’ve been working with Cake for a few years, and it’s hard to imagine not having it in a workflow.

JointsWP
One of my favorite WordPress Frameworks. Combines the latest version of Foundation into a clean set-up. I have some things I don’t use in Joints, but they’re easy to remove or modify to my liking. It’s one of the fastest and smoothest implementations of Foundation for WordPress I’ve found.

There’s a lot more where that came from as knowing one framework is great, but there are newer, more exciting ones coming out all the time. Have I missed anyway? Share the frameworks you’re using in the comments below!



Installing Git & GitHub on OSX Using Terminal

Knowing how to use Git is incredibly important for all developers, whether you’re building a simple HTML/CSS website or making your own operating system. Git allows you to quickly implement version control into your project, but a lot of people–especially developers first starting out have a hard time grasping what exactly Git is and how to use it. But before we even get to using Git, we have to install it first, which for some people, can be a challenge all on its own.

Git is relatively simple to install. Because I use OSX, that’s what this tutorial will be focused around. Here’s what I’m working off of at the time of this tutorial:

OSX Yosemite 10.10.4
Git 2.4.3

There are guides out there that address installing XCode at the same time as you install Git and guides that show you how to install Git through GUI’s and Tools such as Boxen or Homebrew. Those tools are awesome, but sometimes, they cause even more confusion for beginners. This guide assumes that you want to install Git without installing XCode, or if you already have XCode installed, you don’t want the Command Line tools, and just want to install plain old Git without the use of Tools or installing anything else. So let’s get started.

Installing Git on OSX

Step 1: It goes without saying that the first thing you need to do is to actually get Git and you can download it for free on Git’s website. The latest version for your operating system should be available on their homepage: git-scm.com.

Step 2: The downloaded file should a dmg file if you’re installing Git on OSX. You’ll want to double-click on the dmg file to begin the installation process. At the time of this writing, I have the Mavericks version which should work fine for Yosemite as well.

Doubleclick on the file to start the installation process.

Doubleclick on the file to start the installation process.

 

Step 3: Now, unlike most dmgs that you’re probably used to installing, this process requires a little more manual effort. After you click on the dmg, it will mount the Git installation file and present you with the following:

This is inside the dmg file for Git.

This is inside the dmg file for Git.

Step 4a: You want to doubleclick on the .pkg file (in this case, git-2.4.3-intel-universal-mavericks.pkg) to actually start the installation:

Doubleclick this.

Doubleclick this.

If the installation starts, head on down to Step 5. If you get a warning message about not being able to open the file, see Step 4b.

Step 4b: Depending upon your security settings, you may get a warning that it can’t be installed because it’s from a third party developer. That warning might look like this:

Unidentified developer warning. Sometimes thrown when trying to install Git.

Unidentified developer warning. Sometimes thrown when trying to install Git.

If you get that warning, hold down the CTRL key on your keyboard then right-click on the .pkg file and select Open. That will open a different warning dialog that includes an “Open” button this time which will then allow you to run the .pkg file and continue with your installation. In the backend, doing this will also add an exception for the app you’re attempting to install to your security settings. Once it does this, you should be able to just double-click on the app in the future should you need to reinstall it again:

CTRL + Right-Click + Open.

CTRL + Right-Click + Open.

There are other ways to change your security settings to allow you install apps without getting the warning message. For instance, you can go into System Preferences > General  then click on the Lock in the lower left corner, enter your administrative password and under “Allow apps downloaded from”, you check “Anywhere”. This will allow you to install any app regardless of where you got it and if the developer is unidentified, but if you just want to allow Git for now without allowing all other apps, the above technique is a quick way to achieve that.

Step 5: Git will open up the standard OSX installation dialogs from here where you will be able to select the installation type and then proceed to actually install it onto your computer:

Standard installation dialog.

Standard installation dialog.

There is a Custom Install option, but it’s generally recommended to just go with the Standard Install. This step should be relatively straightforward. Once finished, you should see this:

Installation success!

Installation success!

Verifying the Installation & Dealing with Wrong/Outdated Git Version

Like all installations we do, we probably want to verify that everything went off without a hitch. We’re going to verify Git by going through Terminal. A lot of the work developers do involve getting used to the Terminal so if you were afraid of it before, it’s time to get to know it a bit better because you’ll be working with it a lot. Now, this guide assumes that you are totally new to Terminal.

Step 6: Let’s open up Terminal. If you don’t have terminal mounted on your Dashboard, go to Applications > Utilities to find it:

Ah, Terminal.

Ah, Terminal.

Step 7: If you followed my SASS Installation Tutorial, you might be familiar with how we’re going to check for Git; we’re going to ask it for its version number. Within Terminal, type this: git –version, then hit enter/return on your keyboard.

Checking Git version.

Checking Git version.

Step 8a: You should get the version number that you installed, which at the time of this writing, should be 2.4.3. If you do get your latest version to show up, go to Step 9. Otherwise, if you have an older version show up, head on over to Step 8b.

Step 8b: Now, not content with being simple, those of you who have XCode installed, you may already have a version of Git pre-installed on your machines. That version is very likely to be outdated. Here’s what happened when I requested Git’s version:

Thanks for making my life harder, XCode.

Thanks for making my life hard.

Obviously, that’s not the version I downloaded and installed. This is because my computer is currently using the Git that came with XCode’s Command Line tools. You can check if this is the case with you, by typing: which git into Terminal. Once you run which git, if it returns “usr/local/bin”, you’re using XCode’s version of Git. That means we’re going to have to take a couple of extra steps to get to the actual latest version of Git. And if you’re finding yourself in the same boat, here’s how you get to the newest version of Git that you installed. Type this into Terminal:

export PATH=/usr/local/git/bin:$PATH

Hit enter on your keyboard then type this:

source ~/.bash_profile

Now if you check the Git version again: git –version. You should get the accurate version. You’re not done yet, though. Exit out of Terminal by typing: exit, then close out of it completely. Now, reopen Terminal and try checking the Git version again. If you still get the latest version, you’re good to go to Step 9.

If you’re still experiencing issues getting the proper version of Git after restarting Terminal. Or if the new version didn’t appear even after typing in the path above, head to Step 8c.

Step 8c: If you’re still having problems getting the latest version of Git, you may need to update the PATH to override XCode’s version of Git. What we’ll do is override the path that Terminal is getting the old Git version through. To do that, we’re going to declare a path to the newest version of git and write it into our bash_profile file. bash_profile is typically a hidden file on OSX that holds user set preferences. Within Terminal, type in the following (courtesy of Chris Chernoff at BurnedPixel):

echo “export PATH=/usr/local/git/bin:/usr/local/bin:/usr/local/sbin:$PATH” >> ~/.bash_profile

Hit enter and then type in this and hit enter again:

source ~/.bash_profile

What we’re doing is telling Terminal to reference the file we wrote the new Git Path into above, instead of whatever XCode has preset. From here, we can check Git’s version to see if we finally have the new version. But to make absolute sure we’re getting the latest Git version, exit then close out of Terminal. Then start Terminal up again and try getting the Git version again: git –version. You should see the latest version. Now type this in: which git, you should see “/usr/local/git/bin/git”.This is where you want to be.

If you were wondering what the ~ stands for, it is a shorthand way of referencing the home directory. Now you can finally move on to Step 9 and setting up GitHub.

Setting Up GitHub

Step 9: You’ll need a GitHub account first and can sign up for one here: github.com. There are free accounts, low cost, pro accounts all the way up to enterprise. For now, just get a free account. It will give you access to the majority of GitHub’s features and provide you with one private repository.

Step 10: Type in the following: git config –list. You will be shown a list of configurations for your Git installation. If you’re using GitHub (and you should), the first thing you might want to do is edit your username and email address so people working with your projects or looking at them knows who they belong to. To change the username and email, type in this:

git config –global user.name “your name
git config –global user.email “[email protected]

You’ll want to replace the italicized ‘your name’ and ‘[email protected]’ with your own credentials. You can use whatever user name you want, from your real name, to your business name, to a nickname you prefer. However, your user email must be the same user email that you used to sign up for GitHub. Keep the double quotes when you type in those commands too. When you’re done, you can check out your config list again to see the changes you just made. If you mess up setting up your user name or email, you can check to make sure you actually have an issue by typing: git config –get-all user.name or git config –get-all user.email. If you typo’d your first value, you may have typed it up a second time thinking one might overwrite the other and actually end up with two values instead. If you happen to see two values displayed like so:

Shows two values for my user.name, which isn't what I wanted.

Shows two values for my user.name, which isn’t what I wanted.

Type this in to replace the value and resolve the issue:
git config –global –replace-all user.name “your name”

The same goes for fixing two values for your user email:
git config –global –replace-all user.email “[email protected]

Step 11a: I doubt the thought of entering your username and password each time you need to send something to GitHub sounds very appetizing. So let’s automate that process so we can streamline this process a bit. Type in the following:

git credential-osxkeychain

You should get a generalized usage message back that looks like this:

What I got that confirms I have the credential helper.

What I got that confirms I have the credential helper.

If you didn’t get the message above, you will need to install the Credential Helper. To do this head on to Step 11b. If you got the above message, go to Step 12.

Step 11b: Let’s install the Credential Helper. You’ll need to type in the following commands in order, hit enter after every command to execute it:

curl -s -O http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain

chmod u+x git-credential-osxkeychain

sudo mv git-credential-osxkeychain \ “$(dirname $(which git))/git-credential-osxkeychain”
(you will be asked for your administrative password for your computer at this point, type it in and hit enter to continue)

git config –global credential.helper osxkeychain

Finally at this point type in git credential-osxkeychain again and you should get the usage message from Step 11a.

Step 12:  OK, let’s test all of this to make sure it works by performing a commit to our GitHub account. Log into your GitHub account and create a new Repository. On GitHub, you should see a link on the welcome screen after you log in to create a new repository. If this is a brand new account, you will also have a giant image at the top telling you to create a repository.

Making a new repository.

Making a new repository.

Once on the repository creation screen, give your repository a name (I named mine testcommit). You will use this name to send your commits using Terminal so keep it short, meaningful and memorable. Also keep in mind that you can’t have spaces or special characters in the name. You can also set your repository to public or private. I’m going to make a public repository for this tutorial, and if you’re following along looking to make your first test commit and have just a free account, a public repository is probably the way to go for now.

Finally, leave the “Initialize this repository with a README” unchecked. All repositories require a readme file which tells others what the repository is for. We’re going to generate our own README file within Terminal. Now, create the repository and let’s do our first commit.

Step 13: When you send your file to a GitHub Repository, you are “committing” it. This means that you are sending it from your local drive onto GitHub. All of this is done within Terminal so let’s head back there and type this in:

mkdir ~/testcommit

Mkdir stands for “make directory”, we are essentially making a /testcommit directory. Now after we make it, let’s actually move into it. Type this:

cd ~/testcommit

You should be inside the folder ‘testcommit’ now. Let’s initialize Git, type this in:

git init

You should get this message: “Initialized empty Git repository in /Users/computername/testcommit/.git/”. Computer Name is where your computer’s name would be, and testcommit is the directory you created. The last part means you’ve initalized git within that directory. What we’ve just done is create a directory on our computer and made it possible for files within that directory to be committed to GitHub. In fact, if you navigate to Users/computername/testcommit within your file explorer, you should be able to locate it pretty easily.

Step 14: We need a test file to send to our new GitHub repository now. Open up a text editor or code editor and create a sample file. You can put whatever you want it in, or if you’re feeling super lazy, you can download a file I set up here: GitHub Commit Test File (HTML)

Step 15: Throw your file into your testcommit folder that you created on your computer. Let’s finally commit this thing. Type this in:

git add commitfile.html

We are essentially telling Git that we want to add that file to the repository. Now, we haven’t yet gotten our file into our GitHub repository, to do that, we need to push it. Type this into Terminal:

git remote add origin https://github.com/yourusername/testcommit.git

We’re moving into our GitHub repository and getting ready to push files to it up there.

Step 16: Before we can send our files up, we need to make sure our local directory is up to date, otherwise Git will throw an error telling us that we have to pull before we push. First thing’s first, let’s commit. Type this:

git commit -m ‘my very first commit’

We’re telling Git that we’re committing up there. The -m means that what follows (‘my very first commit’) is a message that we’ll be including with our commit. Now, pull the directory by typing this:

git pull origin master

It will pull your GitHub directory and make sure what you have in your local drive is the latest iteration. Now, we’re finally read to push. Type this in:

git push origin master

Once you run that command, your file will be sent over to GitHub and placed into your repository. Check it out in your account on GitHub and you should see your files sitting pretty there.

Before I let you go, one command that you’ll find extremely helpful because I’m positive everyone is going to do this is the remove local repository command. At some point, someone is going to accidentally create a git repository in Terminal in a place they didn’t mean to make a repository. Here’s how you delete it. Go into Terminal, navigate to the directory you accidentally created a repository in by using cd (ex. cd ~/Library) then type this up:

rm -rf .git

Doublecheck that you deleted the repository by typing this:

ls -lah

This will show you all the files, folders and hidden files and folders in the directory you are currently in. If you don’t see a .git file, you’re good to go.

All right, we’re finally done setting up Git and GitHub and we made our first Commit too. This is by far, one of the more complicated tutorials I’ve done because of how many things can go wrong during installation. And I doubt very much that I covered all the bases here. I am far from a GitHub expert and it’s highly possible I missed something or something has been depreciated since I posted this. If you encounter an error or problem setting up Git or GitHub, the very best place to look for help is StackOverflow. Compared to practically all of the people on there, I am a Git Greenhorn.

If you’re looking to do more things with GitHub, this Documentation: Git Reference has pretty much everything you need.

Resources

Git Reference
Burned Pixel, Setting Up Git and GitHub

GitHub Help



CSS: Using Transform: Translate() for Animations and Position

The CSS Translate Transformation function comes in three flavors: translate(), translateX() and translateY(). It can be used to move elements around on your screen, either statically for positioning or coupled with a transition to create attention-grabbing effects. I’ve seen translate used a lot on images and sections to showcase a pull up or pull out type of effect, similar to this:

See the Pen PureCSS Pull Up by Khanh (@ironion) on CodePen.

Hooray, a pull up.

The Translate() Function

The CSS Transform property can be used with a bunch of different CSS functions to generate a variety of effects. In addition to the translate functions, you can also skew, rotate, scale and even perform some 3D functions. A typical transform property with a translate function is written like this:

.sandwich {
transform: translate(valueX, valueY);
}

In the above declaration, we’re using the transform property on the .sandwich class. The transform property takes a function as a value, that function is translate(). Within the translate function, there are two parameters, the first is a value for the X-Axis, the second is a value for the Y-Axis. Written in a functional declaration, it would look like this:

.sandwich {
width: 400px;
height: 400px;
background: #333;
transform: translate(50px, 80px);
}

The above code will statically position .sandwhich 50px from the left, and 80px from the top of its container. It’s more likely that you’ll be using translate in conjunction with transition to create an animation on mouse hover, or when detecting active, etc. than using translate for static positioning. Here’s what it would look like if we were to use translate() with a transition on hover:

.sandwich {
width: 400px;
height: 400px;
background: #333;
transition: all 0.5s ease-in-out;
}
.sandwich:hover {
transform: translate(50px, 80px);
}

In the above code, when a user hovers over .sandwhich, it will move to the right by 50px, and down by 80px. You can think of the values as adding space away from the top, left point of an element. So if we were to declare translate(100px, 400px), that means it will move the element 100px away from the left-most origin point, and 400px away from the top-most origin point.

The TranslateX() & TranslateY() Functions

TranslateX() and TranslateY() work relatively the same as Translate(), only instead of taking two parameters, they will work perfectly fine with just one. You enter in the parameter you want to move the element by either just the X-Axis or the Y-Axis. It probably goes without saying that you use TranslateX() to move elements on the X-Axis and TranslateY() to move elements on the Y-Axis. Here’s TranslateX() in action:

.oranges {
width: 400px;
height: 400px;
background: #888;
transition: all 0.5s ease-in-out;
}
.oranges:hover {
transform: translateX(50px);
}

The above code will move the element with the .oranges class 50px to the right upon a user hovering their mouse over the element. You can always move content to the left instead of the right by using negative values:

.oranges {
width: 400px;
height: 400px;
background: #888;
transition: all 0.5s ease-in-out;
}
.oranges:hover {
transform: translateX(-150px);
}

The above code will move the element with the .oranges class 150px to the left upon the user hovering their mouse over the element. Now, you don’t necessarily have to use pixels with translate, it will work perfectly fine with other types of values too such as percentages, viewport values and even ems. Here’s TranslateY() in action using percentages:

.apples {
 width: 400px;
 height: 400px;
 background: #7c7c7c;
 transition: all 0.5s ease-in-out;
 }
.apples:hover {
 transform: translateY(15%);
 }

We’re moving the element with the class of .apples down by 15% in the above code upon user mouse hover. And whatever we move down, we can also move up using negative values:

.apples {
 width: 400px;
 height: 400px;
 background: #7c7c7c;
 transition: all 0.5s ease-in-out;
 }
.apples:hover {
 transform: translateY(-25%);
 }

We’re moving .apples up by 25% up there upon user mouse hover. Play around with the values a little and see what you can get out of it. There are, of course, equivalent ways to perform translate using Javascript/jQuery too, but I always find CSS to be more straightforward when it comes to these matters. Here’s a CodePen illustrating the three Translate() functions for your perusal:

See the Pen Translate() Demo by Khanh (@ironion) on CodePen.

Styling a CSS Button Click Animation with Translate()

There’s a lot you can do with translate() and one of the more interesting things is creating a button that animates a press when the user clicks on it. For this tutorial, we’re going to use the active pseudo class to detect user clicks, and translate() to animate the button press. Let’s get started by defining our HTML:

<button>Click Here</button>

We’re creating an HTML button element and inside of that element, we have the text “Click Here”, simple enough. The CSS is where we get a little code heavy. Because button elements come pre-styled already with a lot of options that we might not necessarily want, we’re going to overwrite a lot of it so our button looks a little cleaner and more modern. I’m going for this look:

button

So we’re going to use this CSS on our button to get it styled properly:

 @import url(https://fonts.googleapis.com/css?family=Patua+One);

button {
  display: block;
  margin: 0 auto;
  border: none;
  border-radius: 5px;
  box-shadow: 0px 10px 0px #e88372;
  font-family: 'Patua One', serif;
  text-align: center;
  color: #ffffff;
  font-size: 20px;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  text-decoration: none;
  background: #faab89;
  padding: 10px 20px 10px 20px;
  width: 300px;
  transition: all 0.1s ease-in-out;
}

That’s a lot, I know. I’m building a pretty fancy button here so there’s a lot of components that will go into it. Here’s what I’m doing with the button above…

First I import my Google Fonts. Then set my button element to display: block so I can center it using margin: 0 auto on the screen. After that, I remove the default border from the button by declaring border: none, and add some slightly rounded corners using border-radius. I generate a solid shadow using the box-shadow property, normally you will want to write in browser prefixes for border-radius and box-shadow, but I trimmed that code to keep things brief.

After that, we should be in more familiar territory, I’m setting the typeface, the size of the text, the color, aligning the text in the center, forcing the text to be uppercase, removing any text decorations that it might be tempted to add, and adjusting the letterspacing because I didn’t like how it looked initially.

After that I set the color of the button using background, adjust the padding to what I like, set the width of the button, the default cursor when someone hovers over it, and finally, I apply a transition property. The one declarations that you should pay attention to most above is the box-shadow declaration. We’re going to modify that a little bit, so that when a user clicks on the button, we’ll reduce the distance of the box-shadow and make it look like the button is being pressed down.

Most of that you should be familiar with, so let’s put in our active pseudo class and animate this thing upon user click. Funny enough, we already wrote most of our code above, and it doesn’t get any more complicated than that because here’s our translate animation:

button:active {
  box-shadow: 0 1px 0 #e88372;
  transform: translateY(10px);
}

First thing I do is declare the active pseudo class on button. This detects when a user has clicked on the button element then runs our code. Within the declarations, the first thing I did was modify box-shadow, specifically its distance value, changing it from 10px to 1px. This will cause the solid shadow we have under our button to scale down from 10px to 1px upon click and therefore simulating an animated button press.

Next the transform property calls the translateY() function to move the button down by 10px. This is beneficial to us because our original box-shadow was 10px in distance, moving it down 10px lets us keep the button in alignment with the scaling down of the box-shadow so we don’t get any overlapping during the transition. When you’re done, you should have a completed button that looks like this and animates a button press upon clicking:

See the Pen PureCSS Animated Button Click by Khanh (@ironion) on CodePen.

So there you have it, the translate function in CSS used to move elements around and animate a pretty cute button upon click!

Resources

MDN Transform Property Documentation



10 Beautiful Free Fonts on Behance

Behance is like a cave filled with treasure, beautiful free fonts treasure specifically. I’m constantly impressed by the great fonts exclusively available on there so I decided to highlight some of the nicest ones that I’ve found recently. Some of these are completely free for an entire font family, others have some free weights, but they’re all delightful in their own way.

The Beautiful Free Fonts

fontbe01
Moon by Jack Harvatt
A lovely rounded typeface with some nice spacing. Very modern with a touch of friendliness. Great for minimalist headings in your design.


fontbe02
Pier Sans by Mathieu Desjardins
A great structured typeface, another good option for headers and headlines. I’m particularly fond of the R in this one.


fontbe03
Glamor by Hendrick Rolandez
Curly and glorious, like a fancier Bodoni. Glamor would look great set large as a headline on a page or layout.


fontbe04 Linotte by Joël Carrouché (free weight)
Cute and friendly, Linotte’s line is a rounded sans-serif that would be super cute setting a subheading or as an accent type.


fontbe05
Geomanist by atipo
Bold and modern, Geomanist is easy to read and well set. The entire family features an ultra bold that’s great for really heavy type jobs.


fontbe06
Arca Majora by Alfredo Marco Pradil
Tightly kerned and Arca Majora looks great. Would work very well for accent type jobs.


fontbe07
Voga by Charles Daoud
(free weight)
Bold and different, Voga’s unique shapes would look good as an attention-grabbing headline.


fontbe08
Aleo by Alessio Laiso
Aleo is a pleasant, friendly serif with a lot of different features, good amount of readability and a distinctive modern feel.


fontbe09
Rabiola by Raphael Sathler
Serif and classy, Rabiola should be right at home representing a subheading and maybe even body type.



Ailerons by Adilson Gonzales de Oliveira Junior
Ailerons beautiful free fonts
Tall, thin and ultra modern. Ailerons is the kind of typeface that would be great as a headline on a modern or tech-centric design.



WordPress Conditionals for Logged In/Out Users

It happens all the time, you have a logged in user who should be displayed some kind of message or be shown something that a logged out user wouldn’t normally have access to. Typically, this takes the form of a logout button or link if you lost it by deactivating the default administrative bar that WordPress provides. There’s a number of reasons why you would want to do the later, but that means you need to provide a logout link to your users somehow, but you don’t want to confuse people who aren’t logged in. Enter the WordPress conditional statement for logged in users. This is a handy piece of code that is used all the time, and like many such snippets of code, it’s good to have it lying around in case you need to throw it into a template:

<?php
 if ( is_user_logged_in() ) {
 echo '<a href="'.wp_logout_url( get_permalink() ).'">get out of here (logout)</a>'; } ?>

This is a PHP code snippet that starts and ends with the PHP tags. Within the PHP chunk, you have a very simple if statement that asks the website to evaluate if the user is logged in by checking it against is_user_logged_in. If the conditional returns false (the user is not logged in), nothing happens. If the conditional returns true (in other words, the user is logged in), PHP echos a line of HTML that displays a logout link. Within the log out link is a dynamic link to the logout URL.

Let’s say you want to contextually check whether someone is logged in or logged out. We take the basic code chunk above and append an else statement to the end of the if statement in case the conditional returns false (because it’s a bad idea to not have a contingency in the world of code). Here we go:

<?php
if ( is_user_logged_in() ) {
echo '<a href="'.wp_logout_url( get_permalink() ).'">get out of here (logout)</a>';
} else {
echo '<a href="'.wp_login_url( get_permalink() ).'">get back in here (login)</a>';
}
?>

The code chunk above starts off similarly as the one we used prior to it. It checks if the user is logged in. When we get to the else statement after the if statement ends, it handles the situation if the conditional evaluates to false (user is not logged in) and will display a login link leading to the dynamic login page instead. Now, the above conditional is pretty beefy and can work wonders if you want to say something besides login or logout.

If you’re just looking to detect a user’s logged in/out status, WordPress has already written a function that you drop in and let it handle the rest. Here it is:

<?php wp_loginout(); ?>

Easy, peasy. This post turned out a lot longer than I intended, but that’s logged in/logged out conditionals in a nutshell.

Resources

WordPress, Function Reference / WP LoginOut
WordPress, Function Reference / WP Logout URL