• About
  • Forum
  • Write For Us
  • Contact
  • Top 50 Photography Blogs
  • Resources
  • Archives

IndustryDev

Web Design & Photography Blog

  • Design
    • Lightroom
    • Photoshop
    • Bridge
    • Camera Raw
  • Development
    • HTML
    • CSS
    • JavaScript
    • PHP
    • Dev Tools
    • WordPress
  • Photography
  • Blogging
    • SEO
  • Technology
    • Hosting
  • Inspiration
    • Interviews
    • Learning
You are here: Home / Archives for Development
Have a question? Ask it and help others in our new discussion forums.

Website Development & Coding Tips, Tutorials & Techniques

The development section includes posts and articles that cover tips, tutorials and best practices for various areas of coding and web development. Discussion includes fundamental and moderately advanced topics in the worlds of PHP, JavaScript, CSS, HTML, WordPress and more. Additional topics include development tools as well as coverage of online communities that assist with the development profession.

Learning CSS Selector Basics

May 31, 2015

Learning CSS Selector Basics

In order to get into CSS a bit more deeply, I think we need to define what it is that we see behind the scenes. What those chunks of code are that we peek at when spying on someone else’s stylesheet. In order to do that, we need to get into what’s called, “CSS syntax.” Not too much – just a bit.

The first things I’d like to cover is what’s called a “CSS rule” (or rule set). Take a look at the following code and I’ll go over it below.

selector { property: value; }

As you may have deduced from the title of this post, we’re going to discuss CSS selectors a lot. Just as luck would have it, the first part of the CSS rule above is just that – a selector. A CSS selector is what we use to select element(s) we’d like to style on a web page. They’re what we use to grab HTML elements, based on their id, class, type, attribute, and more. After we select an element, we can manipulate (style) it in many different ways.

Now, in between the curly braces is what we call the “declaration block.” Declaration blocks encapsulate, yep, you guessed it – declarations. Each declaration is separated by a semicolon and you can include as many declarations as you’d like inside each declaration block.

If you look at the code above one more time, you’ll notice that a declaration is made up of a property name and a value. These two items are separated by a colon. The property is what we would like to style and the value is what we’d like to do to it. So, for example, a property might be a color and a value might be red. We’ll go over this ad nauseam in this and future posts, but for now, take a look at this simple example:

p {
    text-align: center;
    color: red;
}

In the code above, the “p” is the selector. Everything inside the curly braces is part of the declaration block. Inside this block, we’ve got two declarations. In the first declaration, the property is “text-align” and the value is “center.” In the second declaration, the property is “color” and the value is “red.” Notice how the declarations are separated by semi-colons.

If you’re interested in learning more about CSS syntax, you can visit the source over here. Also, if you’d like to get a jump-start on CSS selectors, you can do that here.

Universal Selector

The universal selector is used when you want to select every element on a page. To take advantage of it, you’d need to use the “*” (asterisk) as the selector. It’s a very handy, but quite far reaching selector, so I’d suggest you use is sparingly. Here’s an example of the universal selector in action:

* {
    text-align: center;
    color: red;
}

If you’ll notice, the code example above is almost exactly the same as the one right above it. All I did was change the “p” selector to the “*” selector. While this alteration was small, it can introduce drastic changes.

In the first example with the p selector, the text-align and color properties were limited to paragraphs. Since I changed the p to an * though, those changes would not only apply to the paragraphs, but all other elements.

Type Selectors

Type selectors are probably the lowest hanging fruit out there when it comes to CSS. These types of selectors isolate the actual element, or node, itself. So, if you wanted to style all p tags or div tags or span tags, you would use a type selector. Let’s go over a few examples:

Let’s say that you have this HTML code on your web page:

<body>
    <header>
        <h1>This Is My Heading</h1>
    </header>
        <p>This is a paragraph in the body section.</p>
</body>

You would easily be able to style these elements with the following CSS:

body {
    background-color: #cccccc;
}

header {
    background-color: #ffcccc;
}

h1 {
    color: #ffffff;
    font-size: 24px;
    padding: 10px;
}

p {
    font-size: 18px;
}

So, if you take a look at the code above, you’ll see that we had a few elements in our HTML that were styled in our CSS. This is the base of what we’ll be going over and this is the base of CSS in general. Grab something from your HTML and style it in your CSS. The only thing that gets more complicated than that is what you grab and how you grab it. Of course, the styling options because more plentiful as well, but to get that down, all that’s needed is experience and a bit of ongoing scavenging of information.

ID Selectors

Let’s say we wanted to target something specific on our page to style. If it’s a very narrow styling, we most likely don’t want to use type selectors. What would suit us well is called an “ID selector.”

Every element on an HTML page can have an ID attached to it. It’s the ID that we can target in our CSS file to give styling to. Now, there are a few rules to follow here. We can’t apply more than one ID to an element and IDs must be unique to each web page, meaning we can’t give a div element IDs of “primary” and “main” and then repeat the “main” ID all the way down the page. We have other selectors for that kind of business. Like I said above, ID selectors are very specific.

Let’s take a look at some code, so you know just what I’m referring to. Pretend that I just updated my HTML page with a few columns. I created a “section” element along with an “aside” element. For both of those elements, I assigned IDs of “primary-column” and “secondary-column” respectively.

<body>
    <header>
        <h1>This Is My Main Heading</h1>
    </header>
    <section id="primary-column">
        <h2>This Is My Left Column Heading</h2>
        <p>This is a paragraph in the left column section.</p>
    </section>
    <aside id="secondary-column">
        <h2>This Is My Right Column Heading</h2>
        <p>This is a paragraph in the right column section.</p>
    </aside>
</body>

Now, in order to style those two columns so they format correctly, I had to add some ID selectors to my CSS file. As you can see, to target an ID, you would type a “#” (hash) and then the name of the ID after that. No spaces. After that, style as you would a type selector.

#primary-column {
    width: 70%;
    float: left;
    border: 1px solid red;
}

#secondary-column {
    width: 25%;
    float: right;
    border: 1px solid red;
}

I’m going to give you a small hint here: IDs are very handy when creating an HTML page. They have multiple uses in not only CSS, but HTML page navigation as well as JavaScript. Keep your eye on the ID attribute and learn more about it here.

Class Selectors

Class selectors are similar to ID selectors in that you can apply them to an HTML element. They have one primary difference though. Class selectors can be applied to multiple elements, not just one. In other words, they don’t need to be unique to a page. Also, you are allowed to apply more than one class selector to an element. While I’m not going to give an example of multiple class selectors per element in the example below, I will go over that later on.

Let’s take a look at some code:

<section id="primary-column">
    <h2>This Is My Left Column Heading</h2>
    <p class="bold">This is a paragraph in the left column section.</p>
</section>
<aside id="secondary-column">
    <h2>This Is My Right Column Heading</h2>
    <p class="bold">This is a paragraph in the right column section.</p>
</aside>

This is the same code as I shared above, but in this code, I added class selectors to both p elements. Basically, I wanted to bold the text within them. Take a look how I styled this in my CSS file:

.bold {
    font-weight: bold;
}

Notice how I used the “.” (period) in front of the selector as opposed to the hash. Just as the word “class” indicates a class in HTML code, a period indicates a class in CSS.

Multiple Classes

Like I mentioned above, more than one class selector can be applied to an element. I gave an example of a class that bolded the text of a paragraph above. Now I’ll give an example of applying two classes to an element. One that bolds the text and one that italicizes it.

<section id="primary-column">
    <h2>This Is My Left Column Heading</h2>
    <p class="bold italic">This is a paragraph in the left column section.</p>
</section>

Let’s say that we would like to make the bolded text in the primary column not only bold, but italic as well. Since we already have the “.bold” class selector applied to the p element, all we need to do is apply an “.italic” selector to that same class attribute. You can see how I did that in the code above. All we need to do now is create the rule in our CSS file.

.bold {
    font-weight: bold;
}

.italic {
    font-style: italic;
}

And with that, we’ll have a bold and italic paragraph.

Descendant Selectors

This is the first area of CSS that’s going to make you think. While type, ID and class selectors are very straightforward, descendant selectors are more creative.

Descendant selectors are sort of like ID selectors in that they can really drill down into the specificity of styling a document. The way it works is this: say you have two “p” elements, like we do in the above examples. One is contained inside a “section” element and one is contained inside an “aside” element. We only want to style one of the p elements. What do we do? Well, I suppose we could create a class or an ID and apply some styles to it, but we now have another choice as well. Take a look at this:

<section id="primary-column">
    <h2>This Is My Left Column Heading</h2>
    <p class="bold">This is a paragraph in the left column section.</p>
</section>
<aside id="secondary-column">
    <h2>This Is My Right Column Heading</h2>
    <p class="bold">This is a paragraph in the right column section.</p>
</aside>

This is the same code as I displayed up above. Now, let’s say that we wanted to give a weird olive green background to the paragraph inside the section element. In this case, we could use a “descendant selector” to get the job done. Here’s the code for that:

section p {
    background-color: #cccc00;   
}

Now, the background for only that p element is green. If you’ll notice in the code, all I did was to use the “ancestor” section selector, type a space, and then use the “descendant” p selector and call it a day. If I wanted to, I could have used the ID selector (or a class selector) in the place of the ancestor selector. That would look like this:

#primary-column p {
    background-color: #cccc00;   
}

This would have achieved the same result as using the section type selector. Think of it as a staircase. You start at the top and keep stepping down to get more and more specific. Of course, you don’t want to go overboard because you’ll end up creating a maintenance nightmare. These do have their uses though.

Pseudo-Classes

Pseudo-classes are a keywords added to selectors that specify a special state of the element to be selected. We’ve seen these all over the place. I remember way back when, when I first began discovering the magic of CSS, I wondered how developers made the links on the page change colors when I rolled over them. Well, as it ended up, it wasn’t too difficult.

I’m going to add a link to the first paragraph in our code:

<p class="bold">This is a <a href="#my-link">paragraph</a> in the left column section.</p>

We can do all sorts of things to this link. I’ll show you some CSS code below and then go over what each pseudo-class does.

/* unvisited links */
a:link { 
    color: blue;
} 

/* visited links */
a:visited { 
    color: purple;
} 

/* user hovers */
a:hover { 
    font-weight: normal;
} 

/* active links */
a:active { 
    color: lime;
} 

If you’ll notice in the code above, I added some CSS code that includes pseudo-classes behind the “a” selector. The way to do this is to use a “:” (colon) after the type selector.

I’ve added some random styling to our link. In the first a:link example, I made our link blue on the page. If someone clicks and visits that link, I made it’s “visited” state purple by using the a:visited pseudo-class. After that, I wrote some code that changes the link text from bold back to normal. Do accomplish this, I used a:hover. Finally, I used a:active to change the link color to lime as long as the link is being actively clicked on.

There’s a heck of a lot more to pseudo-classes than I mentioned here, but this is a good start.

Commenting In CSS

If there’s one thing you want to do inside your CSS code, it would be to add comments. This type of code can get extremely long and confusing and by adding comments to it, you can create sections that’ll make life not only much more clear for yourself, but for others who may be working on your code as well.

I added a few comments to the code above. If you take a look, you should see something that looks like this:

/* this is a comment */

Anything inside the /* and the */ will not be interpreted by the browser and is as safe as regular text. You can even write multiple line comments:

/***************************
****************************
this is another comment
****************************
***************************/

You can add comments anywhere you want in your CSS file, such as inside a declaration block:

a:active { 
    color: lime; /* changes active link to lime color */
} 

You can even make the interpreter ignore some of your CSS code by commenting it out:

/*
a:active { 
    color: lime;
} 
*/

Well, that brings us to the close of another post on CSS. If you have any questions or comments, please leave them below. If you want to check out some more CSS related posts, please take a look at my CSS category. Thanks!

Filed Under: Development Tagged With: CSS


Setting Up Navigation In WordPress

May 27, 2015

Setting Up Navigation In WordPress

I think you’ll agree when I say that website navigation in WordPress is one of the more important areas of creating a template. After all, without navigation, our visitors are going to have a mightily challenged experience while attempting to traverse our sites. With this in mind, in this post, I’m going to cover some of the more critical areas of setting up site navigation in template files.

If you’re creating your own theme in WordPress, you may ask yourself a question. “Hey, how do I add a menu to my WordPress theme?” Well, there are a few steps to complete this task and I’m going to go over them in this post.

add_theme_support

The very first thing you need to do is to get WordPress to recognize that you would like to include a menu in your theme. Without doing this, you’ll notice that there’s no link to “Menus” in your WordPress admin area. In order to have the Menus link appear, we need to add some code to the functions.php file.

add_theme_support( 'menus' );

By adding the above line of code into your PHP block inside the functions.php file, you’ll signal to WordPress that it should give you the ability to create menus for your theme. Once it’s done, you’ll notice that you can now roll over the “Appearance” link in the admin and the link, “Menus” will appear. You can now begin creating custom menus. Before you do that though, you should probably educate yourself on the add_theme_support function and its parameters. The parameter, “menus” is just one of them.

register_nav_menus

Once you’ve got a menu or two created inside the WordPress admin, you need to go back to the functions.php file and tell WordPress that it should actually use the menus you created. There’s a fairly simple way to do this – it again involves a bit of code.

function register_theme_menus() {
  register_nav_menus(
    array(
      'primary-menu'  => __( 'Primary Menu' )      
    )
  );
}
add_action( 'init', 'register_theme_menus' );

There are a few new functions in use here. First, the “register_theme_menus” functions is one we created to hold another function we’ll discus below. This function will encapsulate all menus in our theme.

The second function is called, “register_nav_menus.” This function registers multiple custom navigation menus in the custom menu editor and allows for the creation of custom menus in the dashboard for use in your theme. If you are were interested in only using one menu in your theme, you may want to go ahead and take advantage of the “register_nav_menu” for that. The reason we’re using the function that contains an array is because if we decide to add menus in the future, this function will simplify their addition.

The register_nav_menus function requires the use of a $locations parameter and, again, is used via an array. You can see this in the above code. I’ll show you another example of an array used with multiple menus here:

register_nav_menus( 
  array(
    'pluginbuddy_mobile' => 'PluginBuddy Mobile Navigation Menu',
    'footer_menu' => 'My Custom Footer Menu',
  ) 
);

The $locations parameter uses the menu location slugs and their descriptions.

If you go back to the example above this last one, you’ll see that we have one last function that’s called “add_action.” If I’m not mistaken, I believe I discussed this function in previous posts, but if not, I’ll go over it here.

In this case, the add_action function calls the register_theme_menus as WordPress is initializing. You can see this via the two parameters used inside the function. If you take a look at the add_action function here:

<?php add_action( $hook, $function_to_add, $priority, $accepted_args ); ?>

You can see that we’re taking advantage of the $hook and $function_to_add parameters. The $hook parameter is name of the action to which $function_to_add is hooked. So like I said above, when WordPress initializes, the function gets called. If you’re familiar with PHP or coding in general, you’ll recognize that functions just sit there in sort of a reserve until they are called later on.

So, just to recap what went on above:

1. WordPress had no idea that we wanted to use menus inside our theme. We used the “add_theme_support” function to solve that problem. By doing that, the “Menus” link inside the admin area was enabled.

2. Once we created a menu in the admin area, it sat there in limbo. WordPress didn’t know what to do with it or what “menu area” to attach it to. In order to rectify this issue, we registered a new menu location inside of the functions.php file by using the “register nav menus” function. We told WordPress that we’d like to create an area in which to attach our menu to.

3. Lastly, since our new location was sitting idly inside a function, we need to make it come alive. In order to do this, we used the “add_action” function inside the functions.php file. This called the previous function.

Now, you’ll notice that I’m not covering the other side of creating a menu – the side inside the admin area. Since that’s more of a user interface post and not a development post, I’m going to go over that in another article. For now, I’m simply covering the programming aspect of creating menu locations inside WordPress template files.

wp_nav_menu

Now that we’ve got everything written inside our functions.php file, along with having a menu set up in the admin of our site, we can go ahead and place some code in the header.php file that will tell WordPress exactly where our menu should be located in our template. The function we’re going to use to tell WordPress this is the “wp_nav_menu” function. This function will display the menu that we specify from the “Appearance -> Menus” page.

Before we use the function though, we have to establish a few parameters. We need to create an array that will answer some questions. If you take a look at the functions page in the WordPress Codex, you’ll see all the parameters for this function. While we’re not going to take advantage of them all here, it’s a good idea to scan over what each parameter is capable of for an idea of how you might use them in the future. Check out this code:

$defaults = array(
  'container' => false,
  'theme_location'  => 'primary-menu',
  'menu_class'  => 'no-bullet'
);
wp_nav_menu( $defaults );

In the above code, you can see the array and the parameters we’ve chosen to use. Again, you can visit the Codex page to see what each of these does. Like any variable and just like the functions we wrote in our functions.php page, the “$defaults” variable with its array isn’t going to do much unless we call it. That’s where the wp_nav_menu function comes in. It’ll call the $defaults variable and show our “primary-menu” in the header of our template.

Well, that’s all for my WordPress navigation post. If you have any questions or comments, please leave them below. Also, if you’re interested in more posts that cover WordPress, please check out my WordPress category. Thanks!

Filed Under: Development Tagged With: WordPress


Creating WordPress Page Templates

May 26, 2015

Creating WordPress Page Templates

Once you begin creating templates in WordPress, you’ll quickly realize that the basis of each template is quite similar among them all. If you take a look at my previous post, where I described how one might go about formatting the WordPress loop, you’ll see that the code for the index.php file looks strikingly like the code I’m about to place below:

<?php get_header(); ?>
<section class="row">
  <div class="small-12 columns text-center">
    <div class="leader">    
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>    
      <h1><?php the_title(); ?></h1>      
      <p><?php the_content(); ?></p>     
    <?php endwhile; else : ?>    
      <p><?php _e( 'Sorry, page found.' ); ?></p>    
    <?php endif; ?>    
    </div>
  </div>
</section>
<?php get_footer(); ?>

The reason the code inside the page.php file is almost identical to the code inside the index.php file is because the loop works the same way for pulling posts as it does for pulling page content.

So, why does this code go inside the page.php template? Well, to answer that question, I suggest you review my “WordPress Page & Post Templates” post, where I go over exactly how the WordPress hierarchy functions and why the name, “page.php” is important.

Speaking of the WordPress hierarchy brings me to my next point. What if you want to create a custom page type in WordPress? What does that look like? Well, I went over that in one of my previous posts as well, but I’ll cover it here.

In the example below, I’m going to be placing code inside a template named “page-sidebar-left.php.” If you look at the WordPress hierarchy, you’ll notice that we aren’t bound to any naming conventions when creating custom page types. The naming convention for this is simply “$custom.php.” What differentiates the page among other templates and makes the template available inside the WordPress admin is the comment code at the top of the page. Here, take a look:

<?php
/*
  Template Name: Left Sidebar
*/
?>
<?php get_header(); ?>
<section class="two-column row no-max pad">
  <div class="small-12 columns">
    <div class="row">
      <!-- Primary Column -->
      <div class="small-12 medium-7 medium-offset-1 medium-push-4 columns">
        <div class="primary">    
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>        
          <h1><?php the_title(); ?></h1>      
          <p><?php the_content(); ?></p>      
      <?php endwhile; else : ?>      
        <p><?php _e( 'Sorry, no pages found.' ); ?></p>      
      <?php endif; ?>    
    </div>
    </div>
    <!-- Secondary Column -->
    <div class="small-12 medium-4 medium-pull-8 columns">
      <div class="secondary">
        <h2 class="module-heading">Sidebar</h2>
      </div>
    </div>
  </div>
</section>
<?php get_footer(); ?>

Take a look at the: Template Name: Left Sidebar comment code at the top. This code alone indicates to WordPress that there’s a custom page type available and that it should be included in the “Template” drop-down box inside the page edit admin. Also, if you’ll notice, we don’t really have any dynamic code being pulled into the secondary column yet – we’ll get to that in later posts. For now, focus merely on what a custom page type looks like and how to set one up properly so it’s recognized by the CMS.

If you like reading about WordPress and are interested in how to create templates, you really should check out some of my other posts. You can find them in the WordPress category. Enjoy!

Filed Under: Development Tagged With: WordPress


Understanding the WordPress Loop

May 25, 2015

Understanding the WordPress Loop

If you’ve either looked into developing with WordPress or have developed with WordPress for any length of time, I’m sure you’ve heard of the “WordPress Loop.” The loop is one area of WordPress that you don’t want to skimp on. In order to be proficient in development, it’s important to understand exactly what’s going on. With this post, it’s my intention to help out with that. The good news is, it’s fairly straightforward.

To get the most out of learning how to loop works, it’s a good idea to visit the related page in the Codex. It’s here where much of what you’ll need to know is explained.

I think we’ll get started by looking at a small piece of code that’s shown in the Codex:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    // YOUR CONTENT GOES HERE
<?php endwhile; else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

What you’re looking at above is the bare bones basics of what the WordPress loop can look like. If you’ll notice, there are a few areas and functions in use. I’ll go through things line by line.

In the first line, we have a lot to look at. In this one line, we actually have an if statement, a while statement and the content itself. There are three areas that require consideration.

The first area is an if statement that holds the “have_posts” function and basically asks if there are any posts in existence. If so, then go ahead and continue on to the next area. If not, then jump to the statement that says, “Sorry, no posts matched your criteria.” The have_posts function returns only a yes or no answer and no parameters are allowed.

The second area is a while loop and also uses the have_posts function. This area says that as long as posts continue to exist, then continue on to the next function. If no more posts exist, stop looping.

The last area is used for the content itself and uses the “the_post” function. In the Codex, WordPress says that this function, “Iterates the post index in The Loop. Retrieves the next post, sets up the post, sets the ‘in the loop’ property to true.”

The following lines end the loop and end the if statement.

The above code is one way to write the loop. If you want to see another way, check out this code:

<?php
if ( have_posts() ) {
  while ( have_posts() ) {
    the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <?php the_content(); ?>
  <?php }
}
?>

This might be a bit easier to understand because of the use of the curly braces. You can see more clearly that everything is contained inside the if statement and that the content is contained inside the while loop. But, as you get used to creating and working with the loop, the shorthand that was in the first example is much cleaner to use in your code.

Also, if you’ll notice above, there are a few more functions in use. We already looked at the have_posts and the the_post functions, but we haven’t gone over the “the_title” or “the_content” functions yet.

The the_title function returns the title of the current post. There are a few parameters that you can use inside this function, so if you’re interested in using them, I suggest you read the page in the Codex.

The the_content function displays the contents of the current post and must be used inside the loop. Again, there are a few parameters that you can use here, so if you’re interested, check them out.

To go one step futher, I’m going to build upon my last post and show you some code for how your index page can look. This code should assist in clarifying where you can place your HTML in reference to these PHP functions.

<?php get_header(); ?>
<section class="row">
  <div class="small-12 columns text-center">
    <div class="leader">    
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>    
      <h1><?php the_title(); ?></h1>
      <p><?php the_content(); ?></p>   
  <?php endwhile; else : ?>  
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>  
  <?php endif; ?>    
    </div>
  </div>
</section>
<?php get_footer(); ?>

As you can see above, we’ve included the header and footer files. Also in this code is the wrapper code for the loop. So, outside the loop is some HTML for semantics and styling and inside the loop is a heading tag and a paragraph tag to be used for every iteration of content.

I’d like to finish up this post by giving a few references that’ll help make building your template pages and working with the loop much easier. The first one is “The Loop In Action” page in the Codex. By browsing this page, you can find many great code samples that should give you enough ideas to get started.

Also, if you want to work with the loop, you’ll surely want to know some functions that you can use with it. Guess what? There’s a resource for that. It’s the “Function Reference” page in the Codex. Check this one out, but take a few days with it. There’s a lot to go through. Better yet, just put it in your favorites to look back on when you need it.

If you’re interested in going over more WordPress template concepts with me, be sure to take a look at my WordPress category. I write almost every day, so I think you’ll get a lot out of it. I sure am getting a lot out of my learning!

Filed Under: Development Tagged With: PHP, WordPress


Creating & Including WordPress Header & Footer Files

May 24, 2015

Creating & Including WordPress Header & Footer Files

In most WordPress installs (and websites in general) headers and footers are consistent across many pages. Unless there are special sections that are unique to the majority, visitors will see the same layout, with perhaps some dynamic content, at the top of the page and at the bottom of the page. These layouts are pulled into to the page that’s being viewed by two files – header.php and the footer.php.

Now that we have our index.php page set up, we can go ahead and add some code to pull in, or include, the header and footer files to that page. The code to do this would look like:

// INCLUDE HEADER FILE
<?php get_header(); ?>

    // MAIN CONTENT

// INCLUDE FOOTER FILE
<?php get_footer(); ?>

This is the very beginnings of a template page. As you can see, we have both the header and footer files being included by using two WordPress functions. The first one is the “get_header()” function and the next one is the “get_footer()” function. Remember though, it’s important that the header file be named header.php and the footer file be named footer.php. There are more advanced file names than that available, but we’ll talk about them in a later post. For now, focus on these file names.

header.php

This is where the fun starts. We get to begin building the header.php file out. Below, I’ve displayed some very basic code, including some WordPress functions – just to offer an idea of what might be included in the header file. Of course, there is much more that can go inside this file. I merely wanted to show the bare bones. I’ll go over the WordPress functions below.

<!doctype html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title><?php wp_title( '|', true, 'right' ); bloginfo( 'name' ); ?></title>
            <?php wp_head(); ?>
    </head>

<body>
    <header>
        <h1><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a></h1>
    </header>

Now, if you’re looking at building WordPress templates, it’s assumed that you have an understanding of HTML, CSS and JavaScript. And since you have an understanding of those things, let’s take a look at what’s above.

At first glance, everything looks like what is normally inside a header file. But since we’re dealing with WordPress and its dynamic nature, we need to use WordPress functions. I suppose you could hard code everything into these files, but if you did that, you’d be missing out on much of the functionality that WordPress offers.

The first function you see above is the wp_title function, along with some parameters. This function displays the titles for all posts and pages on your WordPress site. It looks like this:

<?php wp_title( $sep, $display, $seplocation ); ?> 

As you may be able to guess, as the function sits above, WordPress calls the title of the page, uses a pipe as a separator, displays it and displays it to the right of the title. Which makes sense because to the right of this function is the bloginfo function. This function can look like this:

<?php bloginfo( $show ); ?> 

Now, I’m not going to go over all the available parameters for this function in this post because there are so many of them. If you’re interested in taking a look at what they are, feel free to check out its WordPress Codex page. I will tell you, though, that the bloginfo function parameter that’s showing above will display the site title as is stored in the WordPress admin settings.

The next function – and one that’s quite important – is the wp_head function. This goes right before the closing head tag in the header.php file and fires the wp_head action. Basically, this function calls the functions that we placed in the functions.php file. Due to its very dynamic nature, it’s somewhat confusing to wrap your head around. Just rest assured that the functions you coded into your functions.php file will act as you want them to. Functions such as the wp_enqueue_style and the wp_enqueue_script. In this case, the CSS that you coded earlier will appear in the head section of your header.

Finally, we have two more cases of the bloginfo function. In these cases, we’re simply pulling in the site URL and the name, as we did earlier.

footer.php

Below, we have some code that might be found in the footer.php file. As you can tell, this code is a bit lighter than the header code, but in many cases, you’ll find much more than this.

    <footer>           
        <p>Copyright <?php echo date('Y'); ?></p>
    </footer>
        <?php wp_footer(); ?>
</body>
</html>

Above, we have some simple HTML, along with a few more functions. The first one we see isn’t unique to WordPress. It’s actually the PHP date function. If you want to see how to code this, check out this page.

The last function we have is the wp_footer function. This is found right before the closing body tag. Much like the wp_head function, this one is very dynamic. It generally calls in JavaScript files and if you fail to include it, your JavaScript will not work as intended. A good example of how this might work is through the use of the wp_enqueue_script function (I talked about this in my previous post). If you take a look at the “$in_footer” parameter of the wp_enqueue_script function, you’ll see that it relies on wp_footer. Things in WordPress go round and round like this, so it’s important to really learn how this type of code works and how many areas need one another to give you what you’re looking for.

If you’re interested in more WordPress posts, check out my WordPress category. I’ll be writing many more in the future that cover all types of topics.

Filed Under: Development Tagged With: PHP, WordPress


Adding CSS and JavaScript to Your WordPress Theme

May 22, 2015

Adding CSS and JavaScript to Your WordPress Theme

One of the very first areas that needs attention when creating a theme inside WordPress is to add, or include, your style sheets and JavaScript files inside of your template files. Without those, your theme development is going to be quite difficult. In this post, I’ll cover exactly how to go about attaching those types of files to the proper templates.

Importing Code To Your style.css File

It’s really up to you how you want to go about developing your WordPress theme. Some people (myself included) prefer to work live, meaning, code CSS directly inside the style.css file that lives in the WordPress theme folder from the beginning. I prefer to see exactly what each and every change looks like inside WordPress.

Other folks prefer to create an entire template in static files first and then move their code over to include inside the WordPress theme files. If you’re working on a team, this is most likely the preferred approach. Also, if you need approval from a client or are using a framework, such as Bootstrap or Foundation, you might want to take this approach as well.

In this post (and the following posts), we’re going to take the route of creating a static template first and then move the code over to the dynamic WordPress template system.

The first thing we need to do is to include the CSS code into our style.css file. This is a simple copy/paste task. Simply copy what you already coded inside your static template CSS file and paste it inside your WordPress template file. The only tricky part is linking to additional CSS files via the functions.php file.

Linking To CSS Files

If you have additional stylesheet files that you’d like to include in your theme, you would need to create a new folder inside of the theme folder and place those stylesheets inside of it. So your structure would look something like this:

/wp-content/my-theme/css/normalize.css
/wp-content/my-theme/css/foundation.css

Once you have those files inside of your CSS folder, you can insert some code into the functions.php file that will tell WordPress that they exist and that it should use them.

This section involves some code, so I’ll try to explain things as clearly as I can and give additional details as to where you can find supporting documentation for each function used.

First, I’ll show you what the finished CSS include code looks like inside the functions.php file:

<?php
function myt_theme_styles() {

  wp_enqueue_style( 'foundation_css', get_template_directory_uri() . '/css/foundation.css' );
  wp_enqueue_style( 'normalize_css', get_template_directory_uri() . '/css/normalize.css' );
  wp_enqueue_style( 'googlefont_css', 'http://fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic' );
  wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' );

}
add_action( 'wp_enqueue_scripts', 'myt_theme_styles' );
?>

Okay, the first line in the PHP code block is a function with a unique name. You can name this whatever you want, but you should be sure it represents what it’s about. In this case, the “myt” represents the theme name and the “theme_styles” represents what the function is about. The reason you want the name of the function to be unique is to differentiate it from all other functions in your WordPress install. If you’d like to learn more about the functions file, please view this page in the WordPress Codex.

In the next few lines, we use the WordPress “wp_enqueue_style” function. This function is a safe way to add/enqueue a stylesheet file to the WordPress generated page. For documentation on this function, please visit this page or this page.

Now, inside this function, we need to use a few parameters that indicate exactly what the function is going to do. For the first parameter, we use the handle ($handle), “foundation_css” to give a name to the stylesheet we’re interested in attaching. The next parameter is the source ($src) of the stylesheet. To gather the path of where the CSS file is located, we use another function (get_template_directory_uri()) and concatenate the beginning part of the path to the location of the actual CSS file (/css/foundation.css).

The “get_template_directory_uri” function is use to retrieve the template directory URI for the current theme. For more information on this function, please visit this page in the WordPress Codex.

Now, just by simply writing the myt_theme_styles() function, it doesn’t necessarily mean anything is going to happen. It’s similar to creating any function in programming – it sits idly until it’s called. With that in mind, let’s go over the “add_action” function that’s written below the function.

First, what is the add_action function? Basically, the add_action function triggers an event when the hook inside the function is acted upon. So, in this case, we have included the hook, “myt_theme_styles” so when that hook is called, the myt_theme_styles function will execute. Now, I realize we haven’t included the hook in any pages yet, but we will later. It’s important to lay the groundwork by creating functions before calling any hooks.

Linking To JavaScript Files

Linking to JavaScript files via the functions.php file is much like linking to CSS files. We need to first create a /js/ directory to hold our files. In this case, we’ll have three files and the directory structure will look like this:

/wp-content/my-theme/js/modernizr.js
/wp-content/my-theme/js/foundation.min.js
/wp-content/my-theme/js/app.js

Below, I’m going to show you a function that’s similar to the one we used for the stylesheets, but this one’s for use with JavaScript files. Like I did above, I’ll go over what everything means below.

<?php
function myt_theme_js() {

  wp_enqueue_script( 'modernizr_js', get_template_directory_uri() . '/js/modernizr.js', '', '', false );  
  wp_enqueue_script( 'foundation_js', get_template_directory_uri() . '/js/foundation.min.js', array('jquery'), '', true );
  wp_enqueue_script( 'main_js', get_template_directory_uri() . '/js/app.js', array('jquery', 'foundation_js'), '', true );    

}
add_action( 'wp_enqueue_scripts', 'myt_theme_js' );
?>

I’m sure you can see the similarities. The “myt_theme_js” is the name of the function that will hold the specifics of our JavaScript files. The handles, the paths, etc… The first difference that we can see though is the use of the function, “wp_enqueue_script.” While this function links the script file to the proper page, it can also link to it at the proper time, according to its dependencies.

And like the wp_enqueue_style function, the wp_enqueue_style function needs to use parameters as well. Again, I’ll use the first line of the function as an example.

In this case, the handle is called, “modernizr_js” and the path uses the get_template_directory_uri() along with the location of the specific file. While the two enqueue functions do look alike in many ways, the JavaScript enqueue function (in this case) needs a few additional parameters. If you check out the wp_enqueue_style page over at the WordPress Codex, you can see that the additional parameters are the $deps for dependencies, $ver for version and $in_footer for whether or not this script is included at the footer of the page, right before the closing body tag. Here’s what the function can look like:

<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>

In the first wp_enqueue_style function, we use the $handle, $src and the $in_footer parameters and leave the others blank. If you look at further functions a few lines down, you can see that we take advantage of those additional parameters.

Before we finish up this section, let’s take a quick look at how the $deps (dependencies) parameter works. If you’ll notice in the last function:

wp_enqueue_script( 'main_js', get_template_directory_uri() . '/js/app.js', array('jquery', 'foundation_js'), '', true ); 

We use the $deps parameter. The way to take advantage of this parameter is to create an array of files that the file we’re currently calling is dependent upon. In the case above, the “app.js” is dependent upon the jquery (included in WordPress) and the foundation.min.js files, we’ll include those two handles in the parameter. This is important because by doing this, you’re ensuring the dependencies get loaded on the page before the file in question.

Below this, we again use the “add_action” function that I went over above.

——

If you’re interested in more post about creating templates in WordPress, be sure to check out my WordPress category. I’ll be writing more posts covering similar topics in the future.

Filed Under: Development Tagged With: CSS, JavaScript, WordPress


Setting Up a WordPress Theme

May 20, 2015

Setting Up a WordPress Theme

In this post, I’m going to talk about setting up a WordPress theme. I’ll go over where exactly to put your theme files, what order to put them in, what to name them and how to turn your theme on. This isn’t a difficult process, but there are some rules to follow. Let’s get going.

Where Are My WordPress Themes?

I guess we should start with where WordPress themes can be found. There are two perspectives here. The first perspective is from a WordPress user’s point of view. If you have a WordPress install and simply want to know where to upload a theme folder and where you can browse through existing themes on your site, you can do this:

– Log into your WordPress install admin.
– Roll over the “Appearance” link in the left navigation.
– Click the “Themes” link in the next menu.

From there, you’ll notice a few things. First, you’ll most likely see some big squares with thumbnail images inside them. Those are your themes. If you roll over a particular square, you’ll see an option to view a live preview of the theme you’re rolling over and an option to activate the same theme. You also have the choice to view the theme details.

At the top of the page, you’ll see a button that says “Add New” that can be pressed. The following page can be used to search through themes that are located inside the WordPress Theme Repository. If you find something you like, you can install it directly from the repository. Also, on that same page, you’ll see a button that says “Upload Theme” that you can use to upload and install your own theme.

Which brings us to our second perspective. This one is from a WordPress developer’s point of view. Let’s say that you want to get into developing WordPress themes and you would like to know where to store the theme files in you WordPress site’s directory structure. Well, to answer this question is very simple. WordPress theme files are kept in the following directory:

/wp-content/themes/

Inside this directory, you can create a folder with a unique name, such as /my-theme/. You’d store all the files I’ll talk about in later sections of this post as well as in later posts.

Our Theme Template Hierarchy

Since I’ve already covered the WordPress template hierarchy on this site quite a bit, I’m going to keep this section as more of a resource, rather than descriptive or informative. I’ll link to what I think will help in the way of understanding the hierarchy and where you can find information on it. After browsing through the landing pages from the links I’ll give below, you should have an understanding of what the WordPress template hierarchy is and how to go about developing with it in mind.

Template Hierarchy in the WordPress Codex

WordPress Template Hierarchy – A Mini Resource

Working With WordPress Templates

The Anatomy of Your WordPress Theme

WordPress Homepage Templates

WordPress Page & Post Templates

WordPress Archive Templates

WordPress Custom Post Type Templates

WordPress Templates – Media, Search & 404 Pages

Putting Together Your WordPress Theme Folder

In order to begin constructing a theme for our WordPress website, we need to create a directory where all our theme files will reside. We’ll call this the theme folder.

When naming the theme folder (that lives where I described in the first section of this post), we need to be cognizant of similarly named directories in the same directory as our theme. Here’s a hint: don’t name your theme folder with one word. Always prepend something unique before a generic name. So if you would like to create a theme for a cat site, you wouldn’t simply name it /theme/. You would name your theme directory something like, /cat-theme/ or /orange-cat-theme/. By prepending a generically named theme with something more unique, you lessen the risk of conflict with another theme.

In order to get our theme initially off the ground, we’re going to have to create three files inside our folder. These three files are:

style.css
index.php
functions.php

The first two files are necessary for viewing our theme inside the WordPress admin area I spoke of earlier. There is specific text that’s held inside these files that tell WordPress exactly what they are. They give the instructions that tell WordPress what to do with them.

Do you remember when I talked about rolling over the thumbnail box that you’ll most likely find on the themes page inside the WordPress admin? When you roll over that box, a link appears that says, “Theme Details.” If you click that link, you’ll travel to a page that offers all the details for that particular theme. Well, those detail are stored someplace and the top of the “style.css” is that place. Folks in the WordPress community call this area the theme meta information. I’ll give an example of it here:

/*
Theme Name: IndustryDev Theme
Author: Jay Gaulard
Author URI: https://industrydev.com/
Description: Very basic theme that showcases the simplicity of what life on the internet can be.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: responsive-layout, light, silver, two-columns, right-sidebar
*/

To take a closer look at the top of the stylesheet, check out this page in the WordPress Codex.

Just by filling in the meta information for our theme in the style.css file, we’re now able to see our theme available in the themes area of our WordPress admin. All the information we placed in that area is nicely formatted.

What’s missing is the screenshot of what the theme is going to look like. In order to add that to view inside the admin, we’ll need to create a .png file with the dimensions of 880×660. Also, it needs to be named “screenshot.png” and stored inside the theme folder. To learn more about the WordPress theme screenshot requirements, follow this link.

Turning It On – Let’s Activate Our Theme

In order to activate our theme, all we need to do is to head back into the theme page in the WordPress admin, roll over our theme thumbnail and click the “Activate” button. From there, the active theme will move into the first position and be live on the site. If you visit the theme area and don’t see the theme you’re interested in, but see something down below under the heading, “Broken Themes,” it most likely means that a file is mis-named. Check the files over again to be sure they are named precisely as I named them above.

I’m going to be writing posts on how to continue setting up a WordPress theme, so if you’re interested, stay tuned to my WordPress category. Also, if you have any comments or questions, please leave them in the comment area below. Thanks!

Filed Under: Development Tagged With: WordPress


Internal PHP Functions

May 13, 2015

Internal PHP Functions

I am currently embarking in the final stage of Hampton Paulk’s “PHP Functions” course at Treehouse. It’s been a good one so far. I’ve learned a lot. Hampton has a way of feeding information just slow enough as to be easily absorbed.

In this post, I’m going to go over functions that are internal, or built in, to PHP. Some of these functions come standard with PHP (core functions) and some need to have PHP extensions compiled in.

Function Documentation

The most important area you need to concern yourself with when dealing with internal PHP functions is where to find them and how to parse through the documentation. In this section, we’ll go over exactly how to go about doing that.

Finding Functions

So, where exactly can you find PHP’s internal functions? Well, if you follow this link, you’ll see the “home base” for this area on the PHP site. If you’d like to browse through all the internal function categories on the PHP site, you can visit the Function Reference section.

Reading Functions

On the same page, you’ll see a link that says, ” how to read a function definition” and if you click it, you’ll end up at the “How to read a function definition (prototype)” page. This is where you’ll find the explanation of how exactly to pick apart each area of an internal function.

On this page, you get a pretty good breakdown of a function. The PHP manual explains the function name, the history of the function, what the function returns and parameters/arguments for the function. Although the PHP manual uses only the strlen() function for this example, you can use this as a good guide and apply the same principles across all internal functions.

String Functions

One of the more popular sections of all internal functions are string functions. While this section is widely used, Hampton is going over some of the most popular.

strlen

The first function we’re going to look at is the strlen function. This returns the length of the given string. Let’s go over some code.

<?php
$phrase = "This is my first sentence.";
$len = strlen($phrase);
echo $len;
?>

If we look at the above code, we can see that I created a string and set it equal to a variable called $phrase. Then, I used the strlen function and passed through the $phrase variable as an argument. Since that doesn’t output anything to the screen, I set the strlen function to a variable called $len. Finally, I echoed out the $len variable. For this code, the output is:

26

substr

The next function we’re going to look at is called substr. This function returns part of a string. Let’s look at some code.

<?php
$phrase = "This is my first sentence.";
echo substr($phrase, 0);
?>

If we look at the above code, we can see that I kept the initial string and variable. I changed the other areas though. In the case above, I used the substr function to return the entire string. The way I did this was to pass the $phrase variable to the substr function and then begin the output at the first letter. That’s what the “0” is. It’s the first position in the string. Then, I echoed out the function. In this case, the output is:

This is my first sentence.

Take a look at this next example:

<?php
$phrase = "This is my first sentence.";
echo substr($phrase, 5);
?>

In this example, I changed the 0 argument to 5 and now the string is returned beginning at the fifth character:

is my first sentence.

While the previous example began at the fifth character and continued on to output the remaining characters in the string, this next example begins at the first character again and then only outputs the next five. Here’s the code for that:

<?php
$phrase = "This is my first sentence.";
echo substr($phrase, 0, 5);
?>

The output for this example is:

This

Notice that the fifth character is a space and the rest of the string is truncated.

strpos

The next function we’re going to look at the called strpos. This function finds the position of the first occurrence of a substring in a string. Let’s look at some code.

<?php
$phrase = "This is my first sentence.";
echo strpos($phrase, "first");
?>

In the above code, you can see that I, again, kept the first line the same. After that, I used the strpos function and passed into it the $phrase variable. I also passed part of the string into the function. This part is the word, “first.” Basically, I want to see what character position (in the zero based index) the word “first” resides. In this case, the output is:

11

This means that the first letter in the word “first” resides at the eleventh character position in the entire string $phrase.

Let’s look at one final example that combines the two previous string functions.

<?php
$phrase = "This is my first sentence.";
$start = strpos($phrase, "first");
echo substr($phrase, $start);
?>

Now, don’t let this one confuse you. All we’re really doing here is setting different values to variables and then using those variables to get the output we want. The way to think of this is that we’re making something “equal” to something else.

Again, I kept the first line the same. That’s our string. On the second line of the code, I wanted to find the beginning position of the word “first.” We just went over this. The position is 11. I set that output to a variable called $start. Just with these two lines, we have two variables that “equal” some data. Here they are:

$phrase = This is my first sentence.

$start = 11

Now that we know what the string is and we know what the position of the word “first” is, we can do something with it. In this case, we want to output our string at position 11, or wherever the word “first” starts. The way to do this is to use the substr function we went over above and pass to it the $phrase variable. That’s easy – we just did that above. So, if we left things just like that, our output would be the entire string. We want to output the string beginning at position 11 though, and since we have a variable that’s equal to that position, we simple use that variable as our second argument. So, as the second argument, we insert $start. In this case, our output is:

first sentence.

How cool is that?

Array Functions

The next section of internal PHP functions we’re going to look at is array functions. And more specifically, we’ll be going over the array_keys function and the array_walk function.

array_keys

The array_keys function returns all the keys or a subset of the keys of an array. What the heck does that mean? Let’s take a look at some code to get a clearer picture of what this function can do.

<?php
$names = array(
	"Jay" => "Man",
	"Rob" => "Boy",
	"Russell" => "Manboy"
);
var_dump(array_keys($names));
?>

If we create an array called $names and then var_dump that array using the array_keys function, we get this output:

array(3) { [0]=> string(3) “Jay” [1]=> string(3) “Rob” [2]=> string(7) “Russell” }

This doesn’t mean all too much to us, but if you pick apart the output, you can see that we have three values in our array. For each key, in the square brackets, we get the type of value and the length of the value.

If we want to loop through each key and output a message, we can do so with this code:

<?php
$names = array(
	"Jay" => "Man",
	"Rob" => "Boy",
	"Russell" => "Manboy"
);
foreach (array_keys($names) as $name) {
	echo "Hello $name<br>";
}
?>

This will give us the output:

Hello Jay
Hello Rob
Hello Russell

array_walk

The next function we’re going to go over is the array_walk function. This function applies a user supplied function to every member of an array. Again, we don’t necessarily know what that means, so we’ll look more closely through some code examples.

<?php
$names = array(
	"Jay" => "Man",
	"Rob" => "Boy",
	"Russell" => "Manboy"
);
function print_info($value, $key) {
	echo "$key is a $value.<br>";
}
array_walk($names, print_info);
?>

In the code example above, we’re using the same array as above. For the second code block, I created a function called “print_info” and passed through, two values. The first is a variable called $value and the second is a variable called $key. Inside the function, we simply echo out a sentence that says, $key is a $value.

In order to pass through those two variables, we’ll use the array_walk function to go through each key/value pair one at a time. Inside the array_walk function, we’ll pass through our array called $names and the our callback, which is the print_info function itself. We’ll get this output:

Jay is a Man.
Rob is a Boy.
Russell is a Manboy.

I’m not going to lie to you here when I say this one is a bit confusing. I’m still trying to wrap my head around the $key variable. I’m not sure if that’s something that’s internal to PHP and this function. I’m also not sure how it was created. I’ll have to look into it more. If you have any thoughts, please let me know in the comment section below. From that I’m gathering from other sites, it seems like it’s just “there.”

Well, that brings us to the end of Hampton’s “PHP Functions” course on Treehouse. I learned a lot here and really gained an understanding of it by writing it all down. I’m sure that last part about the $key variable will gnaw at me for some time until I figure it out, but otherwise, great course.

If you have any questions about this post, please ask in the comment section below. If you would like to check out some of my other PHP posts, please click the PHP link at the top of this page.

Filed Under: Development Tagged With: PHP


WordPress Templates – Media, Search & 404 Pages

May 11, 2015

WordPress Templates - Media, Search & 404 Pages

I’m coming towards the close of my WordPress template journey with Zac Gordon over at Treehouse. I’ve written about many types of WordPress templates over the last few posts and today, I’m going to go over the ones that are left. The media, search and 404 page templates.

Media Page Templates

I have to admit, I don’t use media pages on any of my websites. What seemed like a good idea years ago has proven to be, well, not so much of a good idea. The reason goes like this – For every post or page you write in WordPress, the search engines count that page as one. For every image you place on a page and link that image to its own page, the search engines count those as individual pages as well. If you have one page with twenty images on it and link to every image using a media page template, you just created twenty one pages. If you don’t know how this can harm you, I encourage you to do a quick Google search for “Google Panda.” If that doesn’t steer you away from using media pages, I don’t know what will.

Be that as it may, and also considering that there are other uses for media pages in WordPress, I’ll cover how to go about setting up custom pages for either mime types or as a catch-all media page for all types of media.

Before we do anything else, let’s first take a look at the WordPress Hierarchy:

WordPress Attachment Hierarchy

As you can see from the above image, the catch-all template for media pages is the attachment.php, This is, of course, excluding the obvious index.php and single.php. If you choose to create a more customized template for your media pages, you can do so by modifying the file names to $mimetype_subtype.php, $subtype.php and $mimetype.php. If you’re wondering what mime types WordPress recognizes, you can check out this page for the allowed default mime types.

I’m going to give you a short example on what your template files might look like if you wanted to have custom pages for images and then custom pages for PNG images. Yes, you can filter down to sub-mime types. Again, you might have a very good reason for doing this, but I’m guessing these types of pages are rarely found.

If you’d like to have an attachment page that will be used for all images, then you would create a template file named image.php. Inside that image.php file, you might find some code that looks like this:

<html>
<head>
	<title>Image Template</title>
	<?php wp_head(); ?>
</head>
<body>	
	<p><a href="javascript:history.back()">&#8592; Back</a></p>
	<div>
	<h1>Image Template</h1>
	<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>		
		<p>MIME Type: <?php echo get_post_mime_type(); ?></p>
		<p>File Name: image.php</p>
		<p><?php echo wp_get_attachment_image( $post->id, 'large' ); ?></p>
	
	<?php endwhile; endif; ?>
	</div>
</body>
</html>

For testing purposes, you can include the “get_post_mime_type()” function, that would display the specific mime type of the page you’re working on and to verify that it’s working correctly.

If you are including PNG files into your posts or pages and are linking to them, and aren’t using the image.php template, you can have WordPress fall back to use a more specific imagepng.php template file. Code inside that file might look like this:

<html>
<head>
	<title>PNG Template</title>
	<?php wp_head(); ?>
</head>
<body>		
	<p><a href="javascript:history.back()">&#8592; Back</a></p>
	<div>
	<h1>PNG Template</h1>
	<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>		
		<p>MIME Type: <?php echo get_post_mime_type(); ?></p>
		<p>File Name: png.php</p>
		<p><?php echo wp_get_attachment_image( $post->id, 'large' ); ?></p>
	
	<?php endwhile; endif; ?>
	</div>
</body>
</html>

Which, as you can see, is very similar.

Now remember, you can set up a specific template for any of the allowed mime types or sub types. Most developers probably create either the attachment.php template or simple use the single.php template if they’re interested in having their media files link to their own pages.

Search Page Templates

I’m going to give you a big heads up on some good knowledge here in regards to search results pages in WordPress. Go ahead and block “/?s” path in your robots.txt file. You DO NOT want any search results pages crawled by search engines. Don’t fall for the, “Just use noindex on those pages…” nonsense that’s floating around on the internet these days. There is no reason why search engines should be crawling these pages and they should be stopped in their tracks. Don’t say I didn’t warn you. There are many a WordPress site out there right now not ranking as well as they should be due to this one area. Don’t become one of them.

Anyway, barring that, you still need to have a nice search results page for your site visitors. Let’s take a look at the WordPress hierarchy to see which template gets used in this case.

WordPress Search Template

As you can see, it’s the search.php template that gets used for website search results. If you set one of those up, the code inside might look like this:

<?php get_header(); ?>
    <div class="container" role="main">
	    <div class="row">
	    	<div class="col-md-12">
			    <div class="page-header">	
			    	<h1><?php wp_title( '' ); ?></h1>
			    </div>
			    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>				    
			    	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>					
					<?php the_content(); ?>
				<?php endwhile; else: ?>
					<p>No results :(</p>
					<p><?php get_search_form(); ?></p>
				<?php endif; ?>
	    	</div>
	    </div>
    </div>
<?php get_footer(); ?>

Now, please be aware, if your website is on the smaller end, you probably don’t need to include a search field or search results page. But if you have a larger website, you would certainly benefit from one.

Also, if you aren’t aware how to include a search box on your WordPress site, you can either use the drag and drop search field widget or hard code the search function into your templates. The code to get the search form is this:

<?php get_search_form( $echo ); ?>

Also, if you are planning on creating a custom search form, please do some reading on the topic in the codex. You can find the appropriate page here.

404 Page Templates

WordPress 404 Page Template

If you’d like to include a custom 404 page for your site visitors to see when they land on a non-existent page, you would set one up using the 404.php template. This template can be as simple or complex as you would like. Some very basic code would look like this:

<?php get_header(); ?>
    <div class="container" role="main">
	    <div class="row">
	    	<div class="col-md-8">
			    <div class="page-header">	
			    	<h1><?php wp_title( '' ); ?></h1>
			    </div>
                <article>
			    <p>This is where your clever content would go.</p>
				</article>
	    	</div>
	    </div>
    </div>
<?php get_footer(); ?>

Please be aware though, you should, at the very least, have a search field that really stands out on your 404 page. If your site is small, at least have some sort or listings for your most popular pages. You want to offer the visitor something to click on if they don’t land on the page they expected to see.

Here we are, at the end of another WordPress template post. I hope you enjoyed what you read and if you have any questions or comments, please leave them in the comment section below. If you’d like to browse some other WordPress related posts, please check out my WordPress category above.

Filed Under: Development Tagged With: WordPress


Getting a Handle on CSS

May 10, 2015

Getting a Handle on CSS

In this post, I’m going to be taking notes on Guil Hernandez’s “Basic CSS” course over at Treehouse. I already took the course a few months ago, but that was before I started this blog. I’d like to take it again for a few reasons.

First, without writing about the course, I have nothing the look back on. It’s important for my learning and retention that I have a tangible something of every course I take. Videos aren’t going to cut it in that department. Not to say that videos aren’t useful for learning in the first place. Now that I’ve had a taste of the good life at Treehouse, I couldn’t do it any other way.

The other reason I’d like to take this course again is I’d like to get a better understanding of what Guil went over. While I do understand and can write CSS fairly well, I’m sure there were a few quiz questions I got wrong at the end of each section. Since I’ve been blogging about the courses, my “correct” rate is nearly 100%. Let’s just say that writing about learning to code helps tremendously.

Before I get into the actual material we’re going over, I want to talk about CSS in general for just a few moments. In the past, I’ve read a bit from more than a handful of websites out there that CSS is a “given” when it comes to designing and developing websites. Well, actually, they said that HTML and CSS are givens, like, “Yeah, you just wake up one morning and know the stuff.” It’s almost like they dismiss CSS and treat it like some red headed stepchild. These days, everyone wants to learn and talk about JavaScript. Well, I’m here to tell you that CSS is rather important and if you’re into designing websites or becoming a WordPress developer, CSS is where it’s at. Make no mistake, once you start getting your hands dirty, you’ll spend a lot of time writing this stuff. It’s what everyone looks at and at this very moment, it’s pretty hot. With the whole responsive thing going on, if you’re a CSS master, you’re in demand.

So, with that said, I feel a little better about continuing on with this post and looking into the basics of CSS.

Resources For CSS

I bought a book on CSS a while back. I keep it handy and enjoy browsing through it for some leisurely reading. I think books are great as reference and can really help out when trying to find something fast, especially if you’re a good bookmarker.

There’s some growing competition to coding books out there though, and that competition is from the web. The difference between books and the web is, obviously, that the web can be updated very quickly. Books, well, to update them, it takes a while. So where on the web can you get some great CSS resources? I’ll list them here:

MDN CSS Reference – An enormous list of everything CSS. Mozilla puts selectors, properties and concepts all on one page. And for ease of use, they list these things alphabetically.

Web Platform Docs CSS – A community and contributor based CSS resource. This website covers learning, selectors, properties, functions, rules and media queries. Also, it gives a heads up on whether of not something is ready for use with browsers or not. Handy.

W3C Cascading Style Sheets – If you like the horse’s mouth and want to read some words from it, here you go. These are the people who can give you the information on the CSS specification, the current state of CSS development and things that are around the corner. If you’re a normal web developer like I am, you most likely won’t need to view this resource often, but it’s good to know it’s there.

Can I Use? – Coding with CSS is sometimes like trying to nail jello to a wall. It’s challenging. The challenge primarily lies in the fact that CSS is a moving target in that it’s never quite finished. There’s a steady flow of improvements, changes and alterations that happen over time. Browsers implement those changes at a varied pace, so as a developer, you really need to know what you can use in your code and what you can’t. Well, with this resource, your life just got a little easier. Click a link and you’ll be presented with information on browser support for just about every bit of code out there.

Adding CSS Styles to Your Page

There are generally three ways to add CSS styling to your page. I’ll go over each one below.

Inline Styles – Inline styles are included directly inside of an HTML tag and has the ability to add styling to a specific element. This type of style is useful if you, for some reason, don’t have access to external style sheets. This type of style is not recommended because, as the number of pages on your website grows, updates and changes to your pages becomes difficult. Also, this adds weight to your HTML pages, which is not preferred. I’ll give you an example of an inline style here:

&lt;h1 style=&quot;color: #CCC; margin: 15px; font-size: 24px;&quot;&gt;Web Page Heading&lt;/h1&gt;

Again, while this seems easy and very direct, get into the habit of avoiding this method of adding styles to your pages for the reasons I mentioned above.

Advantages

– Testing: You can easily test the look and feel of a page by using inline styles.

– Quick-Fixes: Sometimes you need to fix something small and temporarily that you’ll permanently fix later on.

– Tiny Websites: If you want to keep things simple and you operate a very small website, this may be your solution.

– Fewer HTTP Requests: By using inline styles that are placed directly inside HTML tags, you reduce the number of HTTP requests by not linking to external files.

Disadvantages

– Overriding: Inline styles are very powerful and override all other CSS styles for a particular element.

– Every Element: You must apply styles to every page element you want to style. This type of inefficiency is exactly what CSS was developed to avoid.

– Pseudo-Elements and Classes: You can’t use pseudo-elements and classes with inline styles.

Internal Styles – Internal styles are held towards the top of an individual web page in the head section. They are similar to inline styles in that they reside inside an HTML page and that you can use them if you don’t have access to an external style sheet, but the same pitfalls apply to this type of page styling. As sites grow, this type of styling becomes cumbersome and if the CSS code on a particular page becomes verbose, it can affect page download time. I’ll give you an example of internal styling here:

&lt;head&gt;
&lt;style&gt;
body {
    background-color: #f5f5f5;
}

h1 {
    color: #CCC; 
    margin: 15px; 
    font-size: 24px;
}

p {
    font-weight: bold;
    font-size: 16px;
}
&lt;/style&gt;
&lt;/head&gt;

The code for this type of page styling resides inside “style” tags and like I said above, the entire page element resides inside the “head” tags. Unless you have a very good reason, steer clear of this type of page styling as well.

Advantages

– Pseudo-Elements: You can take advantage of pseudo-elements with internal style sheets.

– More Control: Internal style sheets offer more control over page elements than inline styles do. You can apply styles to all elements of a certain type, as opposed to just one single element at a time.

– Fewer HTTP Requests: With internal style sheets, additional HTTP requests are not required.

Disadvantages

– Multiple Pages: Internal style sheets do not span over multiple pages.

– Page Load: Internal style sheets slow the loading of web pages.

– File Size: As your internal style sheet grows in size, so does your page file size, which slows loading as well.

External Styles – The preferred way of adding styles to a web page and a web site is through the use of external style sheets. These types of “sheets” or files, end in a .css extension and can live virtually anywhere. If an external style sheet exists and is live somewhere on the internet, you can use it in your website.

Here is what code inside an external style sheet looks like:

body {
    background-color: #f5f5f5;
}

h1 {
    color: #CCC; 
    margin: 15px; 
    font-size: 24px;
}

p {
    font-weight: bold;
    font-size: 16px;
}

Advantages

– Multiple Pages: External style sheets can span across all your website pages.

– Reduced File Size: By removing code from your HTML documents, every one of those documents becomes smaller in size.

– Pseudo-Elements and Classes: You can use pseudo-elements and classes with external style sheets.

– Grouping: You can easily group your styles to write more efficient code.

– Location: All your styles are kept in one place for maximum efficiency.

– Cache: Once your external CSS document is cached by a browser, it doesn’t need to be downloaded again.

– Pre-Processors: You can take advantage of the power of pre-processors, such as Sass and Less, with external style sheets.

– Separation: External files separate the content and presentation of your website.

Disadvantages

– File Size: External style sheets can get large in size, which takes a while to download.

– HTTP Requests: The more style sheets to call into your document, the more HTTP requests you make to the server. This slows page load time.

Linking & Importing External Style Sheets

So, how do we pull in external style sheets to a web page? Well, there are two ways.

LINK Element

You can use the “link” element inside the head element of your web page to attach an external style sheet to that page. Here is what the link element looks like:

&lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;

@import Command

In order to pull in external styles to your web page, you may also use the “@import” command. This is similar to the previous method and looks like this:

&lt;style&gt;
    @import url('https://www.example.com/styles.css');
&lt;/style&gt;

This method is also used inside the head section of a web page.

Well, that’s it for another fun filled post about web design and development. If you’re interested in more CSS, you can check out my CSS category above. Also, if you have any comments or questions about this post, please leave them in the comment section below.

Filed Under: Development Tagged With: CSS

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • 5
  • Next Page »

Connect With Me

  • Facebook
  • Google+
  • Instagram
  • Pinterest
  • RSS
  • Twitter

RECEIVE MY POSTS BY EMAIL!

Interested in receiving my posts by email? This is your chance! Simply place your email address in the box below and I'll deliver each and every post I write directly to your inbox.

Follow Us on Facebook!

IndustryDev

Check Us Out on Instagram!

Load More…Follow on Instagram

Recent Posts

  • Using the Dust & Scratches Filter to Clean Up a Photograph February 15, 2019
  • Use a Focus Rail For Better Macro Photography February 11, 2019
  • How Do Lens Aperture Sizes Affect ISO Values? February 9, 2019
  • How to Change the Auto-Rotate Settings on your Canon Rebel DSLR Camera February 6, 2019
  • How to Change the Image Review Settings on Your Canon Rebel DSLR Camera February 5, 2019

Most Popular Posts

  • How to Export Video From Adobe Photoshop How to Export Video From Adobe Photoshop
  • How to Set the Photo Quality in your Canon Rebel DSLR Camera How to Set the Photo Quality in your Canon Rebel DSLR Camera
  • How to Resize & Save Files From Adobe Bridge Using Image Processor How to Resize & Save Files From Adobe Bridge Using Image Processor
  • How To Stop the Flash From Popping Up On Your Canon Rebel DSLR Camera How To Stop the Flash From Popping Up On Your Canon Rebel DSLR Camera
  • How to Speed Up & Slow Down Video in Adobe Photoshop How to Speed Up & Slow Down Video in Adobe Photoshop

About IndustryDev

IndustryDev is an online publication that focuses primarily on lovers of the digital world. We write articles that cast a wide net, including those that discuss website development, design and WordPress. We also post, daily, about the image related aspects of the web, including photography and illustration, along with other topics like blogging and SEO.

Read More

RSS IndustryDev Discussion Forum

  • Why Grammar is Important When Writing Blog Posts February 15, 2019
  • Tips & True Costs For Selling Greeting Cards on Etsy February 15, 2019
  • Quick Tips For Proofreading Your Blog Posts February 15, 2019
  • Write With Genuine Integrity For Your Blogging Audience February 14, 2019
  • What Are the Two Icons Inside the Thumbnails in Adobe Bridge? February 12, 2019

Tags

Bridge Camera Lenses Camera Raw Camera Settings Channels CSS Dev Tools Graphic Design Hosting HTML Interviews JavaScript Learning Lightroom Macro Photography Masking Night Photography Photoshop Photo Tips PHP Post Processing Selections SEO Shapes Smart Objects Video WordPress

Recent Comments

  • Jay Gaulard on How to Reset Edit Settings Back to Default in Adobe Camera Raw: “Hi Charleen, I'm assuming you are talking about the small circle identifier that appears in Adobe Bridge after…” Feb 11, 15:57
  • charleen smith on How to Reset Edit Settings Back to Default in Adobe Camera Raw: “Hi Jay, Your instructions for returning a dng to its original settings were very clear. I…” Feb 11, 15:20
  • Jay Gaulard on How to Export Video From Adobe Photoshop: “Hi Mayur, I've actually had this happen. I just need to remember what was causing it. I'll reply…” Feb 5, 08:13
  • luis on How to Change & Limit ISO Settings on a Canon Rebel T6i DSLR Camera: “Thanks!” Feb 5, 00:31
  • Mayur Jobanputra on How to Export Video From Adobe Photoshop: “I just discovered this gem in PS today.. after nearly 10 years of using it!…” Feb 4, 16:02

ARCHIVES

  • 2019: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2018: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2017: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2016: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2015: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

Copyright © 2019 · IndustryDev.com Web Design & Photography Blog · About · Write For Us · Contact · Privacy / Terms · Archives