Tag: wordpress



Conditional WordPress Redirects

Today, we’re talking about conditional ways to redirect a user in WordPress based upon the page they are using to log in. As with all things I do in WordPress, whenever I get a new challenge that takes me a while, I feel the need to share it. Or at the very least, post it so if I ever need it again, I know where to go and grab it.

The latest challenge came from a client who needed an override for users logging in from one particular page. What was happening before was that all users from being sent to a page from the generalized redirect that was already on her website. I spent hours combing through the code of the site getting increasingly frustrated because how many places can someone hide a redirect? Only to realize within the span of a few seconds that the redirect was not being handled in code–but using a plugin. Augh.

After disabling the redirect handled by plugin, the challenge then became how to properly redirect users to a specific page when they were logging in from another specific page. Now, this could be accomplished through user role set-up and using a redirect plugin, but I balked at the hours of tedious work labeling the users who would use one specific page who needed to just access another specific page that wasn’t going to be handled by the redirect. I knew there had to be a way to detect what page a user was coming from and redirect them accordingly.

The Generalized Redirect

First thing’s first, I had to put the direct back in since I disabled it in the plugin. So here’s the redirect that will send all users logging into the page to a specific page…

function login_redirect( $redirect_to, $request, $user) {
return 'site address here';
}
add_filter('login_redirect', 'login_redirect', 10, 3);

That piece of code up there, when you replace ‘site address here’ with your own URL, will send all users logging into your site using your login form to the specified page.

Conditional Redirect Based on Page

The next step was write a conditional statement that evaluated whether the user was coming from a specific page or not. I relied on a very good StackOverflow answer for this one. You can find the original answer here: Thanks to Dominor Novus on StackOverflow

function login_redirect( $redirect_to, $request, $user ){
  if (stripos($_SERVER['HTTP_REFERER'], 'page-permalink-address') !== false) {
    return 'other site address here';
  } else
    return 'site address here';
  }
add_filter( 'login_redirect', 'login_redirect', 10, 3 );

Up there, you are going in using PHP to detect, within the referring website, if a specific query, name or permalink address exists. If it does exist, then your login redirect will send the user to the other site address. Otherwise, if it does not exist, it will send the user to the original site address using the regular redirect.

All this boils down to using a basic if/else conditional. Where I really needed the help was finding out how to get the page to detect the origin site address. Once that was in there, we were open for business. I hope this write up helps someone else struggling to figure out how to override a redirect without having to set up a complicated user role system and use a redirecting plugin.

 



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



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



Why WordPress Themes Won’t Save You Money

While I prefer to do all my work in a 100% customized scenario, a lot of clients do request theme modifications. Many of these themes, they’ve purchased from ThemeForest or some other WordPress theme marketplace. And all that is fine and dandy, if you were just looking for something to build off of. The problem is, working with these themes versus building from scratch isn’t actually any faster or cheaper than finding a good ground up designer and developer to build something from scratch.

I know the allure of themes, many of them come with a lot of great features and WYSIWYG and built-in SEO or whatever. Heck, I’ve been tempted to create my own themes, but haven’t yet had the time to really dive into that kind of project. There’s nothing wrong with using a theme for your website, but you have to keep in mind that you can’t customize it beyond a certain point. Many themes will do really amazing things and offer some level of flexibility, but their basic structures will remain pretty similar because you can’t get away from whatever was originally laid out by the theme developer. And they try, I’m not dumping on theme devs. They do a lot of amazing, gorgeous work. I’m just saying not every business should cram their online marketing into a theme and then worry about customizing it later. At least, not if they want their marketing to be unique and easy to update.

Making the Case for a Ground Up Approach

Here’s the thing with customizing a theme or building from scratch, and I’m going to put it into a list because I am into lists.

1) Your developer will have to figure out how things were organized and coded by the theme developer.

The vast majority of the time, you’re not going to be able to get the original theme developer to come and work on your website. So very often, clients will hire out to another developer to come in and do modifications for them. The general line of thought goes that if you have a theme, most of the framework is already set up, so the developer you’re bringing in just needs to make a few adjustments here and there and add a new feature on top of the existing site and they’ll be done. Right?

The problem is, with every single project, where there’s an existing theme that the client wants to retain, I spend a good amount of time looking at the files, going through the code and getting into the mindset of the previous developer. I’ve done this countless times–hundreds of times–and I still spend time doing this ramp up for every project. The thing is, there are so many themes and developers out there and everyone thinks and codes just a bit differently. Code is an artform in a sense, because no one ever writes code the exact same way as someone else.

Code isn’t just code a lot of the time because while there’s a lot of standardized code, there’s also an unlimited amount of ways that things can be accomplished using code. And with HTML/CSS getting bigger and better all the time, there’s more code and more ways to do things than ever. All of that takes discovery time, which tends to add to development time, which means more money is spent and while the framework might be there, your hired on developer still needs that ramp up time to get used to the existing code.

2) Theme developers don’t support themes forever.

Some developers will stand by their product for the long haul, but many theme developers eventually drop support for the theme because they want to move onto something else–possibly another theme, a custom build for a client, an entirely different industry even. You can’t bet that a theme you purchased will stick around for the long haul because what’s going to happen when the developer stops supporting the theme? It might not continue to work as WordPress versions go up, certain conventions go out of date and your theme can’t be updated otherwise the entire site will break.

Can this scenario happen with a custom website? Sure. But at least with a custom website, you always have the option of calling the developer back and having them update your site to ensure it’ll work for WP versions in the future. I’ve been called in to fix or update themes that have been abandoned before, many of them ceased to work because of deprecated features that WordPress changed or removed.

Many times when a website stops working, or starts throwing blank screens at you, it’s a result of a faulty theme. This could cost a lot of money to get a developer in to figure out what’s going wrong, and related to point #1, it’s going to take that developer some time to absorb the existing code and do something about it.

3) Bloated all-in-one themes will cost you in the long run.

There’s a philosophy that I prescribe to when it comes to developing sites. And that is that I should never allow my client to be shackled by the theme or template that they’re using. What this means is that I will often (if I have the choice) develop from the ground up or choose a theme with as few built-in features as possible.

But, wait–why wouldn’t you just get the theme with the million shortcodes, and hundreds of built-in features that promises to save orphans from burning buildings? Because what happens when that theme stops being supported? Or WordPress updates and half of those built-in features conflicts with the new version of WP? What do you need millions of shortcodes for? Or what happens when you need to add a plugin to your site and that plugin conflicts with something in the theme? It happens all the time, and it’s usually as a result of theme bloat.

Themes are supposed to be about the aesthetics of the website, how it looks, basically. If you needed functionality, that’s what plugins are for. Yes, there is such a thing as plugin bloat too, but at least with the plugins, it’s a simple on or off. Malfunctions in features can be more easily diagnosed, and if one plugin does haywire, you can turn it off, fix it, or replace it. The same can’t be said for an entire theme where one built-in function ceases to work and you’re trapped still using the theme because the other built-in features you’ve been relying on are still fine.

This isn’t to mention that bloated themes often have superfluous features that end up slowing down the website and taking up massive resources. I’ve see themes that were 300MB – 400MB in size. Most of that went into features that most people won’t need. For example, why do you have 10 different pre-made color choices? Who needs all 600(?) Google Fonts natively hosted within the theme? It’s much better for optimization to only take what you need.

4) It’s not just about changing some colors and pictures. It never is.

There are a lot of great themes out there, beautifully written and flexible enough to take a lot of customization. But let’s face it, businesses are unique. Every single one of them has a special circumstance or situation and the only way to ensure that your business stands out in the website field is make sure it’s unique. You can only get so far with a pre-made theme. Sure, you can change the colors, swap out the images, add a couple of lines of code to style things just a smidgen different, but themes have had to be designed and developed a certain way to allow for that customization.

They’ve had built-in restrictions put on them because without those restrictions, things begin to go haywire. Columns don’t line up, images don’t crop properly, colors are mismatched and who knows what else. If things were just a simple color, text and image swap, you wouldn’t be calling in a developer for additional help. And even though you called in a developer and they did everything you needed them to do, a lot of websites built off of themes will forever give off the, “pre-made theme” vibe. That’s really where the whole thing comes full circle, isn’t it?

If you’re already calling in a developer to modify your theme so it looks how you need it to look, why not just build from scratch?

Again, building from scratch isn’t the right choice for every business. Some businesses thrive with premade themes that have had a couple of things about them changed. Others truly do need fully customized solutions. Just be aware that a theme will only cost under $100 if you never plan to change anything about it but the colors, text and images.



WordPress Code Snippet for PHP Display Shortcodes

I’m always finding myself having to look through my notes for this little snippet for php display shortcodes. I use it often enough to have to look for it, but at the same time, not often enough to commit it to memory. So here, once and for all, is the PHP code to display a shortcode in a WordPress template file.

The PHP Display Shortcodes Snippet

<?php
echo do_shortcode("[shortcode]");
?>

Where [shortcode] is the shortcode that you want to display.

While we’re here, what the above code is doing is first identifying itself as a PHP section of code using the opening and closing php tags <?php opens the section of PHP code and ?> closes it, in a similar fashion as opening and closing HTML tags. These two components in the code tell your browser that whatever is contained inside is a segment of PHP.

Then it is calling an echo (printing out) to “do_shortcode”. This means that when you use echo, you’re telling the browser to “display” something in very simple terms. Within the “do_shortcode” function, we’re giving it an argument. That argument is the shortcode itself. We’re sending the value which is whatever shortcode you want to display. This can be a shortcode for a form, gallery or some other plugin shortcode you were provided. Then we close up the PHP section with ?>.

Now I won’t have to dig through my notes for this php display shortcodes snippet anymore. Hooray!

Resources

WordPress Documentation, Do_Shortcode
Describes this little function in immense detail with examples!



How to Remove the Smiley Face on WordPress

So you’re working with WordPress, possibly editing a theme, maybe making your own, or applying a theme you just downloaded. Everything is working OK and looking fine until you get to the bottom of the page and notice this:

Smile!

Smile!

What the heck is that smiley face doing there? At this point, you might be going through all your theme’s options or looking through your CSS and PHP files trying to figure out what the heck is generating that thing and how you get rid of it.

Relax. The smiley is actually a part of WordPress’ stats function. Basically they load a small smiley image onto your page so WordPress can collect information about how many visitors you have, which of your posts your visitors are favoring and so on. In fact, I’ll let WordPress field this question:

In order to tell you all the cool stats about how many visitors you’ve had, which of your posts are most popular, and how people get to your site, we need a way to track things.

We’re able to collect this information by loading a small image to your page when someone looks at it.

And we chose a small smiley 🙂

Source:WordPress.com

OK, that’s just fine and dandy, but what if that smiley is causing a lot of problems for your theme and you just want to get rid of it? Easy!

First, go into your WordPress installation’s Dashboard. Then click on Appearance > Editor. Most themes out there will default to show you the stylesheet.css file in your Editor. If you don’t see stylesheet.css immediately, try to find it on the right hand side where it lists the PHP and CSS files that your WordPress site uses. Sometimes, you may have to navigate further into your file system to locate the right stylesheet.css. But, for the vast majority of us, simply navigating to Appearance > Editor will take us to where we need to go.

Next, scroll down in your stylesheet.css file until you get to the very bottom and add this line of CSS code:

img#wpstats{
 display: none;
 }

Now click on the “Update File” button below your editor textarea and check out your website and the smiley should be gone!

For those of you who aren’t familiar with CSS or WordPress and want to know, “what did we actually do with that piece of code? And is WordPress still counting my stats?”

Yes, WordPress is still counting your stats. What we did with that piece of code was we hid the WordPress Stats image, which in this case, is that little smiley. So browsers will know not to display it, but the underlying purpose of it (to count your stats) is still functioning.

If editing or adding code to CSS or your stylesheet.css file makes you too nervous, there’s another way you can hide the smiley face. If your WordPress site is using Jetpack, you can disable the smiley by going to your Dashboard and clicking Jetpack on the menu on the left. Then click on the “Configure” button under “WordPress.com Stats”. Like this:

Click on the Configure button.

Click on the Configure button.

On the page that opens up, find the checkbox for the option that says, “Hide the stats smiley face image.” Check the checkbox, then click on the “Save Configuration” button at the bottom.

 

Check the box, then save it!

Check the box, then save!

Once you do that, check your website and the smiley face should be gone, but your stats will still work. And there you have it!



Not So Innocent WordPress Themes

The ease of setting up a WordPress blog is fairly common knowledge. WordPress themselves talk about the easy 5-minute installation. And it really is that easy! What isn’t so easy, and what a lot of people often overlook, is the maintenance and security of their blog after the initial installation.

WordPress security is about as exciting as–well, it’s not exciting at all. But like most unpleasant, but necessary things in life, your blog’s security shouldn’t be shuffled into a dark corner and never considered. This post aims to bring to light, one of the most overlooked aspects of running a WordPress blog: Malicious Themes.

While a large portion of malicious themes are free, there are some paid themes that might not be quite so innocent either. Your best defense against having your blog compromised is knowledge and the understanding that no matter how large, small, popular, or private your blog is, malicious code can infiltrate it.

I run a very small blog, do I still need to worry?
Yes. Compromised blogs don’t have to be big or popular. Most people’s blogs get infected with malicious code because they inadvertently installed something bad–not because they were directly targeted. It doesn’t matter how small your blog. Not even if you write in a blog solely for your family and friends, if you download and run a lot of unverified plugins and themes, you run the risk of compromising your blog’s security.

Do I need to a security plugin for my WordPress blog?
Some people run security plugins for their blogs, some people don’t. I can’t advise whether you should or not. It’s a personal decision with pros and cons. If you do choose to use security plugins for your blog, make absolute sure you are installing and using a trusted plugin. Read all the reviews, read reviews on different sites, make sure you are downloading the plugin from a trusted site, see what kinds of problems users have with it. Security plugins can be a lot of work, sometimes they ingrain themselves deeply into your WordPress installation so uninstalling them might be tricky. What you can do if you don’t want to run security plugins is know the risks that are out there and be vigilant about what you install.

With those two questions out of the way, let’s talk specifically about malicious themes. A theme might seem harmless enough. After all, customizing the appearance of your new blog is probably one of the more fun parts of the setup. But not all themes are created equal and not all themes are innocent.

Some theme authors will embed code that redirects, links to, or otherwise manipulates the theme to an unscrupulous website. There’s nothing wrong with a theme author linking back to their own website, and a link back to the original author is common practice. But there are some authors to embed links to sites with poor reputations. Sometimes these links can drag your own blog down, so if you’re trying to get into Google’s good books, having links to bad sites embedded in your free theme that you don’t know about won’t look good. Sometimes it isn’t easy to find these links in your theme because they might be encoded.

Base64 encoding is one of the things to be vigilant about. Very often, the presence of Base64 encoding implies that the theme author has something to hide. Perhaps it’s malicious code, perhaps it’s a link to a bad website, sometimes the purpose is legitimate but can you really take that chance? Decoding Base64 is straightforward. You can plug it into any number of websites you find on Google and discover exactly what’s being hidden from you. I recommend this site: Base64 Decode and Encode. There are a lot of reasons why Base64 encoding exists, but there better be a very good reason for it to exist on your website in the form of a theme.

Another sad development resulting from the glut of free WordPress Themes are ripoff themes. We have counterfeit handbags, counterfeit perfume, counterfeit toys, why not counterfeit WordPress Themes? These are themes that may have been offered as pay themes or were good free themes that were taken, altered to add some malicious code then released as “fresh, new, unique” and of course, “free”.

So how do you avoid downloading a bad theme?

1. Stick to official channels. Googling, “Free WordPress Theme” might yield tons of results, but who’s to say those websites are legitimate and offering good themes? Stick to WordPress.org whose theme repository contains a ton of perfectly nice free themes, Smashing Magazine and other trusted websites often recommend good free themes. But like with all things, you shouldn’t rely solely on a recommendation alone. Read other reviews, and do your own investigations before downloading and installing anything.

2. Consider paid themes. ThemeForest and WooThemes have huge selections of WordPress themes available, many of them are feature-rich, SEO optimized, supported by the authors/developers who made them, are versatile, and look beautiful.

3. Hire a designer or developer. Of course, I have to include this! 😉 Hiring a designer/developer to make you a theme isn’t for everyone–especially not for most personal blogs, hobby blogs, or blogs you keep just for fun. This can get expensive and it still requires plenty of research, but if you’re setting up a business and want to represent yourself well, a free theme that’s got malicious code in it most certainly isn’t going to cut it.



Installing WordPress on XAMPP

One thing that concerns me with some inexperienced web designers, is their penchant for developing or designing a site directly on a client’s web server–either they use a subdirectory on the server or start making changes to the live site itself. There are a number of reasons why developing directly on a client’s live server is a bad idea and I don’t think anyone needs me to point them out. Enter development environments and XAMPP.

XAMPP stands for Cross Platform Apache MySQL PHP Perl. It is, in essence, a development environment for web designers and developers that runs WordPress, Joomla, Drupal, and other similar applications on your local machine, thus eliminating the need to develop on a live server–and thus giving designers absolutely no excuse to develop directly on a client’s live server. Today, I’m going to lay out a step-by-step tutorial to install WordPress on XAMPP on your local machine. Please note that I use Windows 7 for this tutorial, but XAMPP also has an OSX and Linux version. What you use is entirely your choice, but some of the steps outlined in this tutorial may not apply to you.

Here’s the stuff I’m working with:

XAMPP 1.8.1
Apache 2.4.3
MySQL 5.5.27
PHP 5.4.7
Windows 7 64bit
Wordpress 3.4.2

All of the software is current at the time this article was written.

Installing XAMPP

Step One: Download XAMPP. You can get the latest version of XAMPP from the Apache Friends website, here. Download the Installer version. Once you’re done, run the EXE.

Depending on your computer’s settings, you may encounter the above warning message. Note that XAMPP is essentially telling you not to install it into your c:Program Files (x86) folder. Write that down, or commit to memory, then click OK. Follow the directions, let XAMPP install itself into your c: root folder to make things easier for yourself. Once the installation is finished, launch XAMPP’s control panel. If all went well, you should see something similar to this:

Note the green check marks next to my Apache, MySQL, and FileZilla installations. If this is your first time installing XAMPP, you may have the red X’s like the one next to my Tomcat installation instead. What you want to do is click on the red X’s and install at least Apache and MySQL. Once that is done, click on the “Start” buttons to fire up your Apache and MySQL services. If you’re running XAMPP behind a Windows Firewall, you may get a Firewall warning. Make sure you unblock Apache from the Firewall. If everything goes according to plan, your control panel should have Apache and MySQL highlighted in green, and the output at the bottom should indicate that your Apache and MySQL services are running.

Step Two: Time to test your XAMPP install to make sure it works and that your services are running. Open up your favorite web browser, and plug this into your address bar: http://localhost/ (localhost is your local machine). If it’s working correctly, XAMPP’s logo will show up and ask you what language you would prefer. After you select your language, you should see the following screen:

Congratulations, you just installed XAMPP and now have a working development environment. You can use this environment to run installations of WordPress, Joomla, Drupal, Magento, and many other applications. Whoo! That wasn’t too bad, was it? Now, let’s get to the real reason we were here; Installing and running WordPress off of your local machine.

Installing WordPress on XAMPP

Step One: Obviously, we would need to download WordPress first. At the time of writing this article, the latest WordPress version is 3.4.2, but later versions should be able to be run off of your local machine using XAMPP with no problems. So download WordPress.

Step Two: Next, we’ll need to set up a MySQL database for our WordPress installation before we go any further. The easiest way to do this in XAMPP is through phpMyAdmin. You can access this by going to http://localhost/ and clicking on phpMyAdmin under Tools. Alternately, you can go to http://localhost/phpmyadmin/. To create a new Database, click on the Database button as shown below.

Aside: You may have noticed the 127.0.0.1 is the same on your computer as it is on mine. This is because 127.0.0.1 is (in simple terms) your local machine or localhosts’s IP address. prior to running Apache and MySQL with XAMPP, if you tried to access 127.0.0.1 you would likely get an error. People used to (they still might, who knows) fool gullible users into trying to connect to 127.0.0.1 with the promise of some leprechaun gold, only for the user to find that no matter how many times they tried it, connecting to 127.0.0.1 presented them with an error.

Step Three: Under Create Database, give your new database a name. I often run more than one WordPress installation on localhost so I try to keep my naming conventions for WordPress installs something like “wordpress_box” or “wordpress_cashie” or “wordpress_buddy”, depending on what I’m playing around with at the time. Unless you know what you’re doing (and if you do, I wonder why you’re reading this tutorial) leave Collation as it is. Once you give your database a name, click on Create and enjoy this comforting message:

Step Four: Click on your newly minted WordPress database.

What we need to do now is create a WordPress user to avoid using the root user. On a live server, the root user is the one who has all privileges. This can get hairy if you do anything with the root user because you open yourself (or your client) up to a tangled web of security vulnerabilities. It is, in essence, bad practice. Now, if you’re only using this on your local machine, you don’t need to set up a user account and can install directly using the root user because there are, generally, fewer security concerns when it comes to your localhost. But then, just using the root user just because you can would be lazy. And we started this whole journey with the express intent of eliminating laziness and poor practices. So let’s make this WordPress user account. Click on the Privileges button at the top of the screen.

On the next screen, under “New”, click on “Add user”.

Fill in your login information, write down or note your username and password somewhere, and set the Host to either “Local” using the dropdown. Or type in localhost in the textfield. Then scroll down and make sure “

Finally, scroll down to the bottom of the window, and make sure you have all Resource Limits set to 0, and click on “Add user”. Now you should see something similar to this screen:

Okay, now you are all done with phpMyAdmin. Let’s go actually install WordPress now.

Step Five: Unpack your WordPress installation download that you got before. Copy the unpacked wordpress folder, navigate to XAMPP’s htdocs folder, and paste it inside the htdocs folder. If you installed XAMPP in its desired location, your htdocs folder should be located in c:xampphtdocs

Step Six: Go into the WordPress folder that you just copied into htdocs and locate the wp-config-sample.php file. Rename it to wp-config.php and open it in your favorite editor.

Step Seven: Inside your wp-config.php file, you should find places where you can fill in your information. So where it says ‘database_name_here’, fill in your database’s name. For this tutorial, my database was called ‘wordpress_box’, for ‘username_here’, I would use ‘awesome’. Password would be the password you assigned when you created the user for this WordPress installation. ‘localhost’, and the other fields can remain the same. Filling out the form, you should end up with something that looks similar to this (except with your password filled out):

Save wp-config.php and open up your browser again. Now, navigate to your WordPress installation by going here: http://localhost/wordpress/wp-admin/install.php

If everything works correctly, you should be welcomed by this screen:

Fill in your details and click on “Install WordPress” when you’re all done. It should be noted that the username and password you used for your database is not the same as what you will use for your WordPress installation. On a live server, never use the same username for your database and your WordPress administrative account. And always, make sure you have a strong password for both your database and your admin account.

WordPress should install without a hitch and afterward, you can log in to your new installation using the username and password you just created.

Congratulations, you just set up WordPress on XAMPP and now have a fully functioning installation to test your themes, plugins, and whatever else you might fancy. 🙂