Archive

Posts Tagged ‘internet’

Design Patterns in WordPress: The Simple Factory Pattern

May 17th, 2013 Comments off

This entry is part 3 of 3 in the series Design Patterns in WordPress

In this series, we’re taking a look at design patterns and how we can leverage them to our advantage when building products on top of WordPress.

The nice thing about design patterns is that they aren’t explicitly limited to themes or plugins – they are handy in a variety of different scenarios. It’s simply a matter of being able to identify which patterns are applicable to certain scenarios.

In the last post, we reviewed the Singleton Pattern. In this article, we’re going to take a look at the Simple Factory Pattern which is especially useful when you have a number of different classes each of which has a unique purpose and solves a specific problem.

In this post, we’ll take a look at another pattern – the Simple Factory Pattern – which is useful when you have a number of classes each of which has a unique purpose and that can be selected based on certain criteria.

/>

The Factory Method Pattern

The Simple Factory Pattern is actually derived from a pattern known as the Factory Method Pattern which is a slightly more complicated version of the pattern that we’re going to be reviewing.

According to Wikipedia, the Factory Method pattern is defined as follows:

The factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created

Sounds a bit complicated, doesn’t it?

The truth is, it’s actually a really powerful design pattern but it would take a much longer article to discuss it, and it’s a bit out of scope for the purpose of this series.

So, as mentioned, we’re going to take a look at a version of the pattern that’s paired down a little bit and should be more generally applicable to less complicated projects.

Before we do that, let’s come up with a definition of the Simple Factory Pattern:

The Simple Factory pattern returns a specific set of data or a specific class based on its input.

Ah the risk of making a pun, simple, right?

A Note About the Simple Factory Pattern

The truth is, many software engineers refer to the Simple Factory more as an idiom than a full-blown pattern; others consider this a pattern.

For what it’s worth, I see it as a very simple pattern. It has a specific use case that can be easily identified when to use it during the course of development which we’ll review later in this article.

Regardless, I bring this up so that if you see this used as an idiom (or a pattern) used throughout various articles on the Internet, or even in conversation, you’ll know that the developers in question are referring to the same programming strategy – just in a different way.

So Why Does This Matter in WordPress?

Just as design patterns in non-WordPress specific projects, such as larger applications, the design patterns provide a tried and true way to solve a common problem.

It helps to abstract our code a bit, keep our project easily maintainable, easily readable, and can actually help us to keep our code lean. This may result in us actually having more files in our project, but each file should have fewer lines of code.

This means that each file should have a specific purpose that should be clear, not only to us, but future developers as well.

/>

What It Looks Like

Now, before we dive into the diagrams, talking about classes, and the strategies required to implement the actual pattern, I want to mention that we’re going to be taking a simple approach to this.

The thing is, the readership of this blog spans a wide array of experiences – we have some people who are learning to write code; others who are seasoned veterans.

In order to appeal to the majority of the readership, we need to strike a balance. So for those of you who have been involved with software engineering for years, this may seem overly simplistic; however, don’t skim it – perhaps you’ll pick up something new.

For those of you who are beginners or even intermediate programmers, pay close attention to what we’re discussing as it can provide dividends in future (or even existing) work.

The Purpose of the Simple Factory

So imagine this scenario: You’re working on a function that takes in a set of input – usually some type of unique string or integer – and you have this long if/else statement or perhaps you have this large switch/case statement that continues to grow as your project grows.

The problem is that the conditionals become a pain to manage. In fact case conditionals, or the case blocks, may actually end up doing as much work as a certain function should do.

This is where the Simple Factory comes into play. What we can do is abstract the details happening in each of the conditionals into their own class thus making it much easier to maintain and keeping the code much leaner.

And that is the Simple Factory Pattern.

A Look at the Pattern

The Simple Factory Pattern

So here are the key features of the Simple Factory Pattern:

  • Notice that the Plugin class has a private reference to the Factory class
  • The Factory class encapsulates all of the logic to return an object of the type User
  • The User class is a base class for three other classes: Admin, Volunteer, Reader, and the idea is that each of these types are subclasses of users with unique functionality of their own
  • The Plugin will receive a certain type of input that it will pass to the Factory
  • The Factory will examine the input and then, based on its value, will return one of the three user types

Nothing too complicated, right? Honestly, I think that the diagram is a bit more complicated than the principles at play. It really provides a lot of flexibility especially whenever you’re looking to introduce another User type like an Editor or something similar.

Note: This is not to be confused with WordPress’ built-in user types. This is simply an example to show what the pattern would look like.

A Working Example

Now that we’ve taken a look at the diagram for the pattern, let’s take a look at the source code in action. Below, we’ll look at the source code for each class and then I’ll provide a download to a fully documented demo after the discussion.

The Plugin

First, let’s look at the plugin class. Remember, this is nothing more than a prototype of what the pattern looks like. It’s not the same thing as a fully developed WordPress plugin.

factory = new Simple_Factory();
	

	public function get_user( $permission ) 
		return $this->factory->get_user( $permission );
	

}

?>

Notice that the plugin is relatively simple:

  • It includes the simple-factory.php script in the header of the file
  • It then defines a constructor in which it sets the $factory property to an instance of the Simple_Factory
  • The only method available in the plugin is get_user which returns a user based on a type

We’ll see how this comes into play after we’ve examined all of the other classes.

The User

The User is an abstract base class that provides a basic constructor and an abstract function that must be implemented by all other subclasses.

role = $role;
	

	abstract public function get_role();

}

?>

Note that this class is intended to be subclassed by a variety of other classes, each of which we’ll look at in detail momentarily.

The Administrator, The Reader, and The Volunteer

The following four classes are all separate files each of which subclass the User base class. I’ve opted to include them all here together because there’s so little deviation from their actual implementation that it should be easy enough to follow.

The Administrator
role = "Administrator";
	

	public function get_role() 
		return $this->role;
	

}

?>
The Reader
role = "Reader";
	

	public function get_role() 
		return $this->role;
	

}

?>
The Volunteer
role = "Volunteer";
	

	public function get_role() 
		return $this->role;
	

}

?>

As usual, leave me questions in the comments; otherwise, review the code then be sure to read up on The Simple Factory which is the next section – it ties all of this together.

Also, remember that all of this code will be shared at the end of the article along with code comments that describe exactly what’s happening.

The Simple Factory

The Simple_Factory class is really the crux of the entire pattern. Here is where all the decisions are made and the appropriate objects are returned.


Note that the Simple_Factory includes the base user class and its subclasses and then works to return the appropriate type of user based on the incoming set of permissions.

/>

The Advantages of the Simple Factory Pattern

Though it should be a bit obvious by this point in the article, the Simple Factory Pattern provides a number of advantages especially if you’re used to working with large conditionals.

  • It provides an elegant way to abstract your code so there’s less visual clutter
  • It allows you to introduce specialized, focused classes with a single purpose (which is great if you follow the SOLID principles)
  • It makes the code more maintainable as there’s a single place where classes are instantiated, and each class serves a single purpose

Overall, this is one of my favorite patterns simply for the matter of code organization and specialization that it can bring to the table.

/>

Conclusion

Finally, you can checkout the entire source code – complete with documentation and installation instructions – on GitHub using this link.

At this point, we’ve taken a look at three patterns:

  1. The Observer Pattern
  2. The Singleton Pattern
  3. The Simple Factory Pattern

This series could go one for a while; however, I think that we’ve covered enough ground at least to get many of us started with implementing patterns into our work.

So in the last article in the series, we’ll recap what we’ve learned and I’ll also recommend some other patterns, their purpose, and some further points of research that should continue to aid you in continuing to learn about design patterns and their advantages not only in WordPress development, but general software development, as well.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/5pBVx7cN4do/

WordPress Security Threats That You Should Look Out For

March 6th, 2013 Comments off

When running a website on WordPress, it is sensible for you to pay attention to security. There are constant threats to blogs and sites running on WordPress. Oftentimes, you will find out about a security breach after it has happened.

The better option is preventing the threats from materializing than reacting later. Being proactive with WordPress security might be the best thing you ever did.

Here are five WordPress security threats you should look out for and also how you can prevent them.

/>

Login Using Different Combinations

Unauthorized users can attempt to login to your website using a variety combinations of usernames and passwords. With the programs and tools available to them, they will be able to get in eventually. This is known as brute force login.

The good news for you is that you can prevent this by installing a plug-in. The Limit Login Attempts plug-in places a quota on the number of login attempts a user can make. Extending beyond that number, the user is locked out.

/>

Confirmation of Login Information

A major drawback of the current WordPress login form is that it informs the user which part of the login information he/she has gotten wrong. For instance, if the username is correct and the password wrong, WordPress informs the user about it. This makes it easier to use brute force login as the hacker has a clear idea of whether he/she needs to change the username or password.

This issue can be resolved by entering this line of code into your WordPress theme’s functions.php file:

function failed_login () 
	return 'the login information you have entered is incorrect.’

add_filter ( 'login_errors', 'failed_login' );
/>

Global Registration Open

Any person from around the globe can register on your website. This is a feature of all WordPress websites, but is disabled by default. Unless you are targeting a worldwide audience with your side, you should leave this option disabled.

To ensure it’s disabled, go to the Settings tab and access the General settings. There, uncheck the ‘anyone can register‘ checkbox. Also, select ‘subscriber‘ as the New User Default Role as an extra precaution.

/>

Access to Editors

It is usual for WordPress site owners to provide access to editors. While it certainly helps with the design and layout of the website, it also poses the risk of someone gaining access to your dashboard. From there on, that person can change the theme, layout, background, etc., of your website. Enter this line in your functions.php file to prevent unauthorized access:

define ( 'DISALLOW_FILE_EDIT', true );
/>

WordPress Version

Any person with even basic knowledge of WordPress can find out which version of the platform your website is using. Then, they can target particular vulnerabilities in the said platform version to access your website. You can prevent this by changing the information in your page header meta and also in the readme.html file.

To change the meta, use this code:

function remove_wp_version () 
	return '';

add_filter ( 'the_generator', 'remove_wp_version' );

As for the readme.html file, just change the title to anything off the top of your head. Only make sure it wouldn’t be easily deciphered by a hacker. You can even remove it entirely if you wanted to, or just remove the version number from inside the file.

/>

Conclusion

These are five WordPress security threats you should look out for and the ways in which you can prevent them. By no means are these five the only security risks you entail when running a website on WordPress. There are many other ways and tips you can use to make your WordPress site secure and safe from any intrusion or malware. Start by addressing these five threats to get off on the right foot.

Original from: http://wp.tutsplus.com/tutorials/security/wordpress-security-threats-that-you-should-look-out-for/

A Roadmap to Publishing WordPress Themes for ThemeForest

December 27th, 2012 Comments off

So, you think that you’re now skilled enough to create and sell WordPress themes? That’s great! You can choose between selling on your own or using a marketplace. In this post, we’re going to go through a roadmap to get ready and publish WordPress themes on ThemeForest, one of the biggest marketplaces available.

I’m thinking that in the past year, I got better at WordPress enough to create and sell WordPress themes. I’d never go the other way and sell themes from my own website – That’s an expensive option for me since I have to set up payment systems and promote the heck out of the website! That’s why, I started planning a roadmap to publish WordPress themes on ThemeForest, the best marketplace I know to sell many kinds of templates – including WordPress themes.

I’ve come up with 6 important steps to build the roadmap. Let’s go through them now.

/>

Step 1 Choosing the Right Category for Your First Theme

The first step is relatively easy: We’re just going to think.

If you browse through the categories, you can see that some categories have hundreds of themes while some of them have a lot less. For example: While writing this post, I see that there are 952 themes in the Creative category, 757 themes in the Corporate category but only 18 themes in the Technology category and 25 themes in the Mobile category.

But these numbers don’t mean that mobile themes sell less and corporate themes sell more – it means that some categories are more competitive than others. Of course, you can’t ignore the fact that the reason for competition in certain categories is, well, their demands are much more than the others.

Again, less competition doesn’t always mean less profit: Say, if you make a substantial mobile theme, you can become the monopoly of the Mobile category. Or you can go the other way and get right into the competition by creating a corporate theme. If you know how to achieve a competitive advantage, your theme can become one of the most popular themes in that category.

Think it through: Get into competition to sell more or become the monopoly in a noncompetitive category?

/>

Step 2 The Importance of Functionality

You can’t publish a static, boring theme with limited functionality and expect high sales. People don’t buy your themes to replicate your demo content – they look for flexibility and options that can turn the theme’s demo into something they can use.

In my opinion, you should focus upon at least three points of functionality:

  1. A neat set of shortcodes
  2. A good rate of flexibility
  3. Functionality that can benefit from WordPress’ core features

While thinking about what functionality to include, remember this: Functionality bloat could repell people from buying your themes, too. There’s no way that anybody would want or need to use 500 different fonts and 250 types of backgrounds – maybe except for a funky font showcase.

How to Serve the Functionality With Plugins

While writing this article, Stephen Harris, one of our best authors here on Wptuts+, had a different idea about shortcodes:

Shortcodes should never come bundled with a theme. Once you switch theme, your posts will be left with shortcodes appearing in them. If the idea of the shortcode is to style content (a button, or a styling some generic ‘note’ for example) then this should instead be done via TinyMCE button which produces the necessary html.

We can’t ask people to install additional plugins manually because it’s extra work for everyone and some people might even fail to see this requirement and then complain about the theme, not fulfilling its promises about functionality. That’s where the TGM Plugin Activation library comes in handy.

The TGM Plugin Activation Library

The TGM Plugin Activation library allows us to require and/or recommend plugins from both WordPress Plugin Repository and external sources (including your theme’s subfolders). By following the instructions, you can include this library in your theme to display notices to the user and allow them to install the required (or recommended) plugins even in bulk.

Since it prevents the website’s content from breaking when the user switches themes, this is probably the best way to include the functionality for your theme’s users.

/>

Step 3 Outsourcing: No Reason to Reinvent the Wheel… or jQuery

If you decide to be the owner of every pixel and byte of the theme, you’ll probably need a few extra months to finish them all.

You don’t have to design the background patterns, icons,


lines or code the slider, tabs, multi-level menus etc. all by yourself. As long as you understand how licenses work, you can use resources on the internet.

TLDR Legal: A Great Place for Learning About Licensing

TLDR Legal is a great website, aiming to explain open source licenses in plain English. Since most of design & code resources are licensed under open source licenses like MIT or GNU, you can check how they work from this website before using.

You can search for licenses or “terms” (limitations) by clicking the “reverse search” button inside the search box. In our situation; we could enter the term “Commercial Use” to see which licenses allow us to use the work in commercial projects. As far as I can see, MIT and GPL-3 licenses allow people to use the work for commercial projects for free – but don’t forget about other terms!

However, if you want to use an item sold on the Envato network, say, a WordPress options panel for your theme from CodeCanyon, the extended license rights are explained already in plain English. To summarize: You can use stuff for commercial use, if you pay for the Extended license. You can read more about Envato’s approach on license in the Envato Knowledgebase.

Personally, I think I’m going to buy an extended license for an options panel (and maybe some shortcode plugin) from CodeCanyon and use a neat slider and background patterns that are licensed under MIT or GPL3. You should think about it, too: What would slow you down if you want to design or code it yourself? Remember: If you overwhelm yourself with loads of work, you might even think about giving up; but if you outsource too much, you might have a hard time because of overspending or you might get confused because you need to learn every bit of the code/design you use.

/>

Step 4 Let’s Get Designing!

I have to back down a little bit here: No matter what I say or no matter how great you code your theme, great design is always the best dealmaker. A theme could be breaking apart in IE9 or it could have the worst options panel ever made but it could be sold if it’s easy on the eye, it could be purchased by hundreds of people. I’m not encouraging you to disregard everything other than design – I’m telling you that even if you code an awesome theme, you’ll still have to make your theme look good in order to sell it.

Notice that I didn’t say anything on how you should design a theme. Because I can’t. Nobody can tell you how to design – in fact, it could be better if you ignore people who claims to know what kind of design looks better. This is not a problem with just one correct answer: Your design could be the most unusual design ever made, yet it could also be the top selling item on ThemeForest.

Plus, if you have a design that stands out over other themes in the same category, you might have some great competitive advantage. Don’t go crazy, though: People like change but might resist on a revolutionary design.

/>

Step 5 Getting Your Hands Dirty With Coding

I always hate the “coding” phase; but when I finish and see my code working, that gives me one of the best feelings that I can get from a computer screen.

Needless to say, you should code clean, and that means sticking with the WordPress Coding Standards. You could also refer to the “Theme Development” page on the WordPress Codex for further information.

Since this is a roadmap and not a step-by-step tutorial on theme creation, I shouldn’t tell you how to code except further than reminding the coding standards. But I can tell you where to code:

  1. Sublime Text: I think it’s one of the most favored code editors available for web developers. It has of course syntax highlighting, it’s pretty fast, it allows you to control your entire project… and best of all, there’s a free course at Tuts+ Premium for Sublime Text 2 by Jeffrey Way!
  2. Notepad++: This is my favorite code editor and I’ve been using this open source program for at least 3 years. It doesn’t offer much functionality like Sublime Text, and it lacks the “good looks” of Sublime Text, but it’s a fast code editor which could even be a replacement for the classic Notepad of Windows. It can also be extended with plugins.
  3. Brackets: Being developed and maintained by Adobe, this new code editor has some very interesting features like “instant preview” on your browser, without the need for reloading every time you edit the code. Jeffrey Way has a video review for this tool, too. It’s called A Peek at Brackets.

Other than that, you should also check the general file preparation guidelines in the Envato Knowledgebase.

Then you submit your work. Congratulations!

/>

Step 6 Keeping Up the Good Work

Publishing a theme doesn’t mean that you’ll just wait for the money to roll in after the theme gets listed. You have to take care of everything you’ve submitted in order to continue earning from them. If you don’t, your sales will eventually stop.

You have to provide at least a decent level of support and update the theme when new versions of WordPress are released. ThemeForest has the comments section for each theme which can be a good option to get feedback and provide support, but you can open up a “support forum” on your website in order to provide better support. Plus, some users might help each other there.

Implementing new design trends and updating outsourced utilities might be good for competition, too. For example: If you have a slider that needs to be updated, update it with your new version. Or, if a new design trend emerges (like “responsive design” emerged earlier this year), update your theme to be compatible with that trend to attract users who follow these kinds of trends.

/>

Conclusion

I tried to think of the steps to take while creating a new WordPress theme for ThemeForest. If you have anything to add, please share your comments below. Thanks for reading!

Original from: http://wp.tutsplus.com/tutorials/theme-development/a-roadmap-to-publishing-wordpress-themes-for-themeforest/

Introduction to the Genesis Framework

November 26th, 2012 Comments off

There are a lot of WordPress frameworks out there. Most of them are paid and some surprisingly are free like Hybrid or Thematic. Most WordPress users who are using frameworks either use Thesis or Genesis. “Why use a framework?”, one might ask. It’s because of its simplicity and straightforwardness. Although it’s difficult to switch to a framework, and learning it in the initial stages can be quite difficult, it will definitely pay off in the long run.

There can be a lot of reasons for opting to use a framework over a standard WordPress theme. Some of them may be:

  • Clean and semantic Code
  • More control over the look and feel of your website
  • Better SEO options
  • A lot of themes to select from
  • Option to create your own child themes, (More on child theme in a minute!)
  • Custom widgets and design layout
  • And yes the prompt customer service

I might have missed a few, but these are pretty much those that needed to be mentioned.

/>

What Are Child Themes?

In simple words, Genesis is the framework just like a picture frame hanging on a wall. This frame is empty and you will require a picture so that the viewers can see it. This picture is the child theme, and the viewers are your daily visitors on the website. There are many organizations that provide you with custom built child themes. The child themes have their own cascading style sheets and you can easily edit them. The child theme also has a functions.php file, in which you can add your own custom code and make it operate as you like it. The child theme actually contains three files and the rest of the files are in the Parent Theme.

/>

Why Use a Framework?

The answer is simple, once you start to use the framework you’ll get used to it in no time. You can make your own changes in a pre-existing theme that came with it, or you can build yourself the dream theme that you always wanted to.

/>

Which One: Thesis or Genesis?

Genesis is built for Designers and Thesis is built for Programmers

Choosing between these two top notch frameworks in the WordPress family is quite difficult. When choosing between them, you might have to consider your options. They may vary from person to person. Some people would like a very simple and minimalist design and some may like completely the opposite. When choosing between these two frameworks design may be an important factor. Genesis provides more designing options as compared to Thesis, but Child themes of Genesis are less in quantity as compared to those of Thesis. There are many child themes available for Thesis on the internet, both free and paid. So to use the entire designing capabilities of the Genesis Framework, one must be willing to get their hands dirty with hooks and short codes. Some people also say that Genesis is built for Designers and Thesis is built for Programmers.

/>

Designing Options

Design plays a very vital role in our life. It is a very important element of nature and if you look around your room, it will have a certain reflection of who you are. If you look at the design of the entire Envato network, you will get the idea. Integrating design in websites is becoming more and more important these days. Users tend to spend more and more time on websites which have new and innovative designs. When it comes to designing your websites, Genesis gives its users a lot of options. There are premade child themes which you can edit. A lot of layout options are also included. You can also change the typography by adding Google Fonts and so much more.

/>

Genesis Hooks

Every framework comes with its own set of hooks, which lets you take control of the overall look and feel of the design. These hooks provide the user with complete command even on minor details. Plus you can change it anytime you want and that too, very easily. So you pay for it in the start and it saves you time and work in the long run. Looks like a nice deal to me!

It provides you with good functionality; you can add and remove many widgets. Your custom widgets will also work the same way with the framework as if with any other design. You can spice up the sidebar with social media sharing buttons, a twitter plugin and a lot more.

/>

Search Optimized

The framework is nicely built keeping in mind SEO. Its code is semantic and you will never need any SEO plugin like Yoast or All-in-One. According to StudioPress, they have collaborated with Greg Boser who is a partner and SVP of search marketing powerhouse BlueGlass Interactive.

All the options related to SEO are integrated into the framework and you require absolutely no plugin. The SEO options also provide Custom Canonical URLs for post and pages. Also there is an option for Custom Redirect URL and you can use this to redirect your previous post to any URL you want to. One thing that I liked the most about its SEO options was that it offers custom keywords for every article that you post on your website. It becomes easy for you to add keywords for your article without needing any additional plugins. So search engines will have an easier time finding the article based on the custom keywords!

/>

What to Do When You Are Stuck at Some Point

If you are like me and poke around the code, I am sure that you will get stuck at some point or another. There is no need to panic because there are tons of articles and tutorials about Genesis which will help you out. And if that specific problem still exists you can always go for the Support provided by the StudioPress Team. They will surely remove any errors that you might have made when digging into the code.

There are also some basic tutorials on the StudioPress website. They also provide video tutorials, which are great and easy to follow, and they will surely help you get going with the framework after you have purchased it. Also there are many developers that you can hire if you have extra coins in your pocket!

/>

Setting Up Genesis on Your WordPress Installation

It is as simple as it can be. Extract the genesis folder on your desktop; now you have a new folder named genesis.

Next, log in to your FTP account with your FTP software. I use FTP Zilla. Navigate to wp-content/themes and upload the genesis folder you extracted earlier. After the upload is complete, we’ll upload a child theme for the Genesis Framework. You can buy child themes from StudioPress’ website or you can make one yourself. The Child theme basically functions as a costume for our website. We can change the look and feel of our website by editing our Child theme.

That’s it pretty much. You have just setup your first WordPress theme using the Genesis Framework.

/>

Styling Your Genesis With Responsive Childtheme

Instead of building your own child theme from scratch, you can download a sample child theme from StudioPress’ website. It has all the basic code in there to make it look like a webpage. Most of the changes you will be doing are to the “styles.css” and the “functions.php” files. The best thing about the sample child theme is that its layout is responsive which is pretty sweet considering that it is free.

/>

Design Yourself a Child Theme

The first step is to design yourself a child theme in Photoshop or Gimp. I am going to make the old WordPress Kubrick theme for this tutorial as an example. The reason why I am using the Kubrick theme is that it’s simple and easy to follow. You can also design your own website in Photoshop and can convert it into a child theme for Genesis.

/>

Design the Header

We’ll work our way by changing the background color of the website first. In the image file you can see the background is of grayish scale. So we’ll add some styling in the CSS file of the Sample Child theme. Make sure that you are editing the file of the sample child theme and not that of the Genesis Framework. Now we’ll add the following code in our styles.css file and save it.

body
	color : # d5d6d7;

Remember that the child theme has its own styling already there. All you need to do is find the appropriate div or class and add styling to it.

Similarly stylize the header of your website. I will add the CSS code for styling the header and making the text centered with the following code.

#wrap 
	box-shadow: 0 0 5px #999999;
	margin: 15px auto;
	padding: 0;
	width: 960px;

#header 
	background: none repeat scroll 0 0 #FFFFFF;
	border-radius: 5px 5px 0 0;
	margin: 0 auto;
	min-height: 140px;
	padding: 10px 10px 0;

#title-area 
	background: none repeat scroll 0 0 #73A0C5;
	border-radius: 5px 5px 5px 5px;
	float: left;
	overflow: hidden;
	padding: 30px 0;
	text-align: center;

/>

Typography

Now we’ll shift our focus to making the general typography of the website. For the title to be displayed in a white color we’ll find the div of “title” and the hex code for white color. Similarly we’ll add white color to the div of “description”.

#title a, #title a:hover 
	color: #FFF;
	padding: 0 0 0 20px;
	text-decoration: none;

#description 
	color: #FFF;
	font-size: 14px;
	padding: 0 0 0 20px;

I like the Typography of the Sample Child theme, so I will leave this as it is. The best thing about Genesis is that it uses Google Fonts. This makes it easier for you to incorporate different styles in your website, just the way you like it. Google Fonts are free and you can use theme on your website. You can find out more on using Google fonts here.

/>

Navigation and Sidebar

You can setup Navigation to show up in the Genesis theme settings. Scroll down to Navigation Settings and choose the one according to your needs. Before you can add a navigation bar, you will have to make a “New Menu” from the “Appearance” tab. Add a new menu and create new links for your pages or categories into the newly created menu. Since there is no menu in this example we’ll select not to show the Primary Navigation.

Sidebar styling is a lot easier and doesn’t require any coding or maybe just a little, depending on your needs. To add different elements in the sidebar, go to the Widgets area from Dashboard and add a Search box. You can also add Recent Posts, Categories and other widgets as per your choice.

Although the Sample Child Theme has better styling than the one in the original design, it’s all about personal opinion. For the styling you can remove the bottom borders and make the size of the font small in the widgets’ CSS which will make it look similar to the original design.

/>

Final Touches

For the final touches we’ll add some personalization to the theme. For this we’ll edit the header of the styles.css. Although it is supposed to be the first thing to do when building a theme, but for some odd reason I usually do this last.

Next, we’ll change the footer text which still displays the “Sample Child theme”. To edit it, open up your child theme’s functions.php and add the following code at the bottom.

/** Customize the credits */
add_filter( 'genesis_footer_creds_text', 'custom_footer_creds_text' );
function custom_footer_creds_text() 
	$creds = '

'; $creds .= 'Copyright © '; $creds .= date( 'Y' ); $creds .= ' · Kubrik Genesis · Built on the Genesis Framework'; $creds .= '

'; return $creds;

Change the mywebsite.com to your desired one. Hit save and upload it to the server and refresh your website. Your settings will take place right away.

/>

Conclusion

The theme options of Genesis somewhat fall short when compared to those of Thesis. Also if there was a sitemap generator built into Genesis it would have been great. But I guess that you never acquire something which is complete in every aspect. There is no need to buy an extra developers license to use Genesis on more than one website, thus you end up saving money. Other than that, the security and support, both are top notch.

For designing your website, it seems easy and uncomplicated. The changes are usually very easy to make. You get a responsive theme to which you can make changes depending on your taste. You get to use thousands of Google Fonts for your website. You can make your website as colorful you like. There are also some crafty themes from StudioPress with some artistic flavor. You get good and powerful SEO options for your website. For me it’s a pretty well rounded offer. So all in all it’s a nice framework and you can learn it in a very short span of time. How have you found Genesis? Let us know in the comments below.

Original from: http://wp.tutsplus.com/tutorials/theme-development/introduction-to-the-genesis-framework/

Two Ways to Develop WordPress Plugins: Functional Programming

November 21st, 2012 Comments off

This entry is part 2 of 2 in the series Two Ways to Develop WordPress Plugins

This part two of a series looking at two different programming styles (sometimes called programming paradigms) that you can use when writing WordPress plug-ins. In part one Tom McFarlin covered object-oriented programming. In this part we’ll be looking at functional programming.

Because the experience level of readers varies, we’re going to be talking about programming at a high-level, so if you’re a beginner, then you should have no problem following along. If, however, you’re a more experienced developer, then you may find more useful information later in the article.

/>

What Is Functional Programming?

Functional programming is probably the style with which you are most familiar – and almost universally – is the style used in the various WordPress code snippet websites floating around the internet. For this reason it can sometimes be viewed as ‘entry level’ programming: the style employed by beginners until they’ve learnt to master object-oriented programming. This is incredibly misleading, because while functional programming is much simpler, it is not in itself inferior.

Functional programming emphasises the evaluation of functions, and avoids the notion of states or objects as opposed to object-oriented programming which encourages thinking about code as acting on object(s), using methods to change those objects, or interact with them. Let’s look at a very simple example comparing the two styles:

	// Functional method
	function add_two( $n ) 
		return $n +2;
	
	$a = 2;
	$b = add_two( $a ); // $b = 4;
	// Object oriented method
	class Number 
		var $value = 0;
		function __construct( $a ) 
			$this->value = $a;
		
		function add_two() 
			$this->value = $this->value +2;
		
	}
	$a = new Number( 2 );
	echo $a->value; //Prints 2
	$a->add_two();
	echo $a->value; //Prints 4

This very simple example illustrates the fundamental difference in style of the two paradigms: functional programming focuses on passing arguments to, and receiving values from functions. There are no ‘objects’ that are being acted on, only parameters and return values. Conversely, the object-oriented approach assigns an object various properties (in our case a ‘value’) and methods act on those properties.

/>

Functions: The Basics

Defining functions is very simple:

	function add( $number, $number2 = 1 ) 
		// Perform code acting on passed variables
		$sum = $number + $number2;
		// Optional, if needed you can return a value
		return $sum;
	

Once the function is declared it can be used anywhere in your plug-in – in other words it has global scope.

	$a = 4;
	$b = 7;
	echo add( $a, $b ); // Prints 11

Functions must have unique names. Redeclaring a function will throw an error. Since your code will be running alongside other plug-ins, themes and WordPress itself you should never use generic names. Instead you should prefix your function names with something unique (like the name of your plug-in). />

You may have noticed that in the definition of add, the second argument is set equal to 1. This sets a default value for $number2 (in this case, 1), and by doing so makes the argument optional. If the argument is not supplied, the value is taken to be the default value:

	echo add( 4 ); // Prints 5
	echo add( 4, 1 ); // Prints 5

On the other hand, no default value is provided for the first value, so omitting that argument will throw an error

	echo add(); // Throws an error as $number is not defined

You can also have a variable number of arguments. Inside the function we can use func_num_args() to get the number of arguments received, while func_get_arg() allows you access a particular passed variable, indexed from 0.

function sum() 
	// Get the number of arguments given to sum()
	$number_args = func_num_args();
	$sum = 0;
	if ( ! $number_args )
		return $sum;
	for ( $i = 0; $i < $number_args; $i++ ) 
		$sum += func_get_arg( $i );
	
	return $sum;
}
echo sum( 1, 2,  3, 4 ); //Prints 10
echo sum( 1, 2 ); //Prints 3
echo sum(); //Prints 0

The above can be used in object methods too. Finally, by declaring a variable as `global` you can access the variable from inside a function.

	$a = 'Hello';
	$b = 'World';
	function hello_world() 
		// This is necessary to access $a and $b
		// declared outside of the function scope.
		global $a, $b;
		$b = $a . ' ' . $b;
	
	hello_world();
	echo $b; // Prints 'Hello World'

Using globals is generally discouraged. Particularly since two plug-ins using the same name for a global variable can cause either one or both plug-ins to break. If you must use a global variable, again ensure it’s unique by prefixing with your plug-in’s name. />
/>

Why Use Functional Programming?

Deciding which programming style to use comes down to judgement – and yes – personal preference. It is not more right or wrong to use functional over object-oriented programming, but more often than not there is one style which is better suited for what you’re trying to achieve.

Sometimes object oriented programming simply isn’t necessary, and only over complicates matters, or introduces superfluous code. An example might be the various ‘utility’ functions WordPress provides. These are generic functions which serve to perform a particular purpose. For example wp_trim_words( $text, $num_words ) simply trims the given string to a certain size (in words). It wouldn’t add anything to define wp_trim_words() instead as a method belonging to some object, and would result in uglier code. With functional programming it takes one line.

One advantage of functional programming, particularly for beginners, is its simplicity. You do not have to worry about static, private or protected functions – they are all global. Neither does the notion of static variables exist. At the very basic level your function returns an output derived from what you’ve given it. For example, get_the_title( 7 ) will return the title for the post with ID 7.

Another advantage of functional programming is that functions are accessible globally. With object-oriented programs, in order to act on a specific object, you need to pass around that object. This can sometimes be tricky. To illustrate this let’s take an example from part one:

class DemoPlugin 
	public function __construct() 
		add_action( 'wp_enqueue_scripts', array( $this, 'register_plugin_scripts' ) );
	
	public function register_plugin_scripts() 
		// Register plugin scripts
	
}
$demo_plugin = new DemoPlugin();

When WordPress stores the register_plugin_scripts() method so that it can be called when the wp_enqueue_scripts action is triggered it does so by referencing not only the method, but also the object $demo_plugin. This is because the same method for different instances of an object are considered different methods – that is, $demo_plugin->register_plugin_scripts() and $copy_of_demo_plugin->register_plugin_scripts() are not the same. This may seem odd – but methods can behave differently for different instances of the same class, so we need to reference both method and instance.

But why does this matter? It makes it very difficult for a third party plug-in or theme to unhook that method, since to do so they would need to call:

	remove_action( 'wp_enqueue_scripts', array( $demo_plugin, 'register_plugin_scripts' ) );

But in general they won’t have access to the $demo_plugin variable. (Note: if the method is declared static, then you can get around this).

/>

Object-Oriented and Functional Programming in WordPress

Of course object-oriented programming has its advantages, as discussed in part one. As Tom also mentioned, it is unavoidable when using WordPress’ widget API. Another common example is WP_Query(). Here an object oriented approach is clearly the best: you have an object (in this case a query), which has various properties (i.e. search criteria, pagination information, matching results) and you want to act on that query (parse it, generate and sanitise the corresponding SQL, and return the results).

WP_Query() demonstrates how powerful object-oriented programming can be when used correctly. After initiating the query:

$the_query = new WP_Query( array(...) );

Not only can you access the results, but other information too such as, pagination values: how many pages of results there are, which page is being viewed, the total number of results, and the ‘type’ of query, e.g. $the_query->is_search(), $the_query->is_single() etc. There is also the entire ‘loop’ infrastructure;

	if ( $the_query->have_posts() ) 
		echo '
    '; while( $the_query->have_posts() ): $the_query->the_post(); // The Loop echo '
  • ' . get_the_title( $the_post->ID ) . '
  • '; endwhile; echo '
'; wp_reset_postdata();

Which hides all the internal juggling of results and globals behind a human-friendly API.

So what about get_posts()? This just serves as a wrapper for WP_Query(), and simply returns an array of posts matching the query. As such, you don’t get the ‘bells and whistles’ of WP_Query(), but it is slightly more efficient. So whether you should use get_posts() or WP_Query() depends on your use case (for example, whether you require pagination or not), but it’s also down to personal preference.

	$results = get_posts( array( ... ) );
	if ( $results ) 
		echo '
    '; foreach( $results as $the_post ) echo '
  • ' . get_the_title( $the_post->ID ) . '
  • '; echo '
'; }
/>

Summary

Hopefully these two articles have helped highlight the advantages and disadvantages of these programming styles. The take away point is that there is no right and wrong here, and each programmer will have their own personal preference. But some contexts lend themselves more readily to a certain programming style – and as such you should expect your plug-in to contain a mixture of both.

Original from: http://wp.tutsplus.com/tutorials/plugins/two-ways-to-develop-wordpress-plugins-functional-programming/

Why WordPress Is So Good

October 2nd, 2012 Comments off

Since 2006, I’ve been working with WordPress daily. My first work with the platform was in a blogging situation where I used a basic self-hosted site to keep a blog about my life. Before that, I had been using Google’s Blogger which was becoming a little unwieldy for what I wanted to do.

That’s why I made the leap to self-hosting and that’s when my journey with this incredible piece of code started.

Since then, I’ve been using WordPress for any number of different situations. I’ve used it for blogging, news verification, liveblogging, ticketing for events, event management, portfolio publishing, magazine style sites, a home for a discount card and many more. I’ve worked it into websites for churches, innovation management consultancies, concert promoters, news organisations, creative industries companies, concert promoters and loads more.

In fact, I’ve never found a project that WordPress didn’t work for – sometimes with a little coding, sometimes right out of the box.

Recently, I’ve had a lot of questions about WordPress from people who I’ve worked with in various other capacities or come across in day to day life. I always enjoy helping them get started with publishing information about whatever sector they’re working in or interested in.

That’s why I wrote the book WordPress for Mere Mortals which has just been published as an e-book by Rockable Press.

/>

The Common Problems

There are a lot of questions that get consistently asked and which seem to really confuse people. That’s OK. WordPress is so flexible that there’s bound to be a lot of confusion. Here are some of the most confusing things that we can clear up pretty quickly:

Q) What’s the Difference Between WordPress.org and WordPress.com?

A) WordPress.com is run by a company called Automattic, and offers a version that’s taken care of for you which you can find by going to WordPress.com – all you have to do is write your blog posts. If you want to do something more complex, head on over to WordPress.org to download the WordPress software and get started, but remember you’ll need somewhere to host the files yourself.

Q) What Belongs on a Page and What Should Go in a Post?

A) A page contains information which is unlikely to change over a great deal of time. For example, your contact page is probably going to remain largely unchanged over months or even years. A post contains something which is time sensitive like a message about an offer that your cafe has on at the moment or news about a big client your law firm has just won.

Q) How Do I Change the Design of My Blog?

A) Easy! WordPress streamlined this process for you by allowing people who write code to create themes. Themes mean you don’t have to know anything about design. You can find some great ones on ThemeForest.net for starters. Just download them to your desktop and then log in to your WordPress installation (yoursite.com/wp-admin) > select Appearances > Themes > Upload your ZIP file and then ‘Activate’

Q) Can I Upload Pictures?

A) Yup! Uploading pictures and other media (video etc.) is really easy. Just start writing a post and when you want to put a picture into the text, just select the ‘Upload Media’ button which is right above the text formatting options. Find the file on your computer, then press ‘Upload’, and then select ‘Insert into post’.

/>

Why Should You Use WordPress?

There are many reasons why you would want to use WordPress above other choices. Here are some of them:

  1. Availability of plugins – a plugin is a package of code that someone has written to accomplish a specific task. For example, Akismet is a plugin which makes sure that WordPress doesn’t get completely spammed by wayward spammers. Some more fun examples of things that plugins can do are embedding Flickr streams, put one of those neat sliding images that you see on websites these days, make your events calendar look and work better than the default one. Plugins are available freely and most of the time don’t cost anything or much. If you want to find a plugin to accomplish your goal, just Google this formula “‘insert your problem here’ WordPress Plugin (Free)”
  2. Designers are on your side – the design community loves WordPress and you can be sure that there’s already a theme out there that already fits what you’ve got in mind. That can save you a whole bunch of money. As previously mentioned, you can just head over to Envato’s ThemeForest where there’s a wonderful selection. One of the best new themes is Radiant by Brandon Jones (http://themes.mdnw.net/?theme=Radiant)
  3. You’re in good company – There’s an impressive list of people who are using WordPress already. They include: Playstation, Smashing Magazine, The Who, Tom Jones, Pac-Man, GigaOM and many more. If those guys are using WordPress, they must all agree on something.
  4. Support is great – If you ever get stuck, you’re never alone. There has never been a time in all the years I have used WordPress that I haven’t found the answer to a question by Googling the problem. The WordPress.org support forums are incredible places to find answers to questions with a very dedicated community who love to help.
  5. />

    WordPress for Mere Mortals

    As I mentioned above, I wrote the book WordPress for Mere Mortals to help people get over some of the problems that they have with starting out on WordPress.

    We’ll start off with why WordPress is the tool for your project. Did you know 60% of the internet is powered by the WordPress platform? Everything from your neighbor’s blog about her dog Chuck to the Prime Minister of Great Britain’s website! WordPress is very diverse and you can do anything you want with it.

    Then we’ll move on to some very practical guides about buying a domain name, finding a web host and choosing a theme for your site before we take a look at what a post is and how that’s different from a page.

    We’ll also go through the process of managing all of the content on your website, and uploading pictures. Then we’ll also cover stuff like how to embed video from YouTube. Finally, we’ll have a look at some plugins that will help super charge your site.

    If you want to get started with WordPress or you know someone who wants to start a website or blog, you should get this book, WordPress for Mere Mortals. I wrote it so that anyone could understand it – even after the introductory chapters, we still use very little jargon.

    And, if you have any questions about getting started with WordPress, you can always tweet me on @iammarcthomas – I’ll give you a hand or point you in the right direction.

    Original from: http://wp.tutsplus.com/articles/news/why-wordpress-is-so-good/

The Theory of Unit Testing, Part 2

July 26th, 2012 Comments off

This entry is part 2 of 2 in the series The Theory of Unit Testing

In the last article, we began talking about the theory of unit testing in WordPress. Specifically, we reviewed our work on unit testing themes and plugins then began to discuss units of code, how this impacts our testing, and we reviewed unit testing in the larger world of software development.

We’re going to continue discussing the theory of unit testing in WordPress, but are going to be doing so through the perspective of how it can help identify problems, drive architecture, document the project, and more.


Finding Problems, Saving Time

Recall from earlier in this series, that the traditional way of doing unit testing is this:

  • Write a test, run it (knowing that it will fail)
  • Write the function to make the method pass.
  • Run the tests. If the test fails, continue working on the function; otherwise, move to the next.

Yes, the first step is a bit dogmatic. Why waste minutes running something you know is going to fail, right? Still, you get the idea. But as you begin to apply this particular technique to development, you’re going to find that you’ll develop a certain rhythm to writing your code and that’s part of the whole goal.

But that’s only half of it – unit testing can actually help you detect problems earlier on in development.

In order to understand, this it’s probably best to back into the idea.

Let’s say that you’re working on a feature for a WordPress-based project where you’re going to allow users to create a user account without actually logging into the WordPress dashboard. This assumes that you’ve got a page template setup to handle registration, the necessary validation in place, and the code for generating passwords and emails.

You load the page up in your browser, try to create a few users – some with the same email address, some with improper passwords, some with illegal characters, etc. You get the point – there are n-number of ways for the validation to pass and to fail. This is rough! This means that every single time the user registration function is changed, you have to perform the same n-number of registrations to make sure nothing is broken.

Or you can write a suite of tests to take care of it and run them all each time the code changes.

So, yes, writing unit tests can take a lot of time up front but look at the amount of time saved each time you modify a unit of code. It’s well-worth it and this can help identify problems early on – that is, before it’s released into production – that could have been missed because someone forgot to simulate one permutation of the test.


Self-Documenting

When it comes to writing unit tests, you’re not only improving the quality of your code by ensuring that it actually works, but you’re inherently providing developer-oriented documentation.

If you’re unit testing the functionality that you’re building into your product, you’re going to be providing documentation for how functions are intended to work, when they should fail, and when they should pass.

There are a few assumptions that come with this: Specifically, that you’re logically naming and grouping your functions and their associated tests and that you’re properly testing each function.

Through PHPUnit, the WordPress Unit Tests make it easy to perform assertions that are easy to read. You simply state assertTrue, assertFalse, or any other assertions available on the functions that compose your project.

Following with our example above, this means that you could write a function to make sure that the user registration function fails when trying to register with an empty email address:

$this->assertFalse( registerNewUser( '' ) );

A simple example, perhaps, but the point remains: Your code becomes self-documenting and it only requires that you write clear unit tests.


Architecture

Perhaps one of the most understated advantages of unit testing is that it can help drive the architecture of your project. Typically, theme or plugin development can start one of two ways:

  1. Listing out functions, sketching the user interface, then write code
  2. Draw out a diagram of how files will all work together, then write code

These aren’t inherently bad, but I think they are weak (and I’ll be the first to admit that I’ve done both more than I’d like to share!). But the “write code” step assumes a lot, doesn’t it?

For anyone that’s been writing code for an ample amount of time, you are all too familiar that you end up hitting that point where your realize, “Oh … I didn’t think of that.”

If you’re lucky, this usually means you can write a helper method or another conditional to handle the case that you neglected, but in the worst cases, it means that you may have to rework your entire class or your entire set of functions to accommodate this problem.

Unit testing, although not perfect, can help to mitigate this.

Consider the fact that, from the very beginning, you’re listing out all of the functionality that you want your theme or plugin to offer. You’ve yet to write any code but perhaps you have some type of sketch of the UI and/or a set of class diagrams.

Next, you begin to write out the tests that you’re going to be writing in order to test your project. Recall that part of unit testing is breaking down code to the most atomic unit possible, thus you’re tasked with writing unit tests for each of these, ahem, units.

Because of the nature of unit testing, you’re inherently thinking about your code differently: rather than “write code,” you’re thinking “write tests,” and because you’re having to think at a more atomic level, you can’t help but consider fringe cases that are so often lumped into “write code.”


The Language of Your Code

As developers, we’re far too comfortable with using conventions that continually reinforce that we write code. By that, I mean that we tend to provide abbreviated variable names, cryptic function names, and class names that may not mean anything to anyone outside of yourself or the team that’s working on your project.

Unit testing isn’t necessarily the key to writing code that’s easier to read, but it can go a bit further in helping to provide cleaner function names.

Recall from that first programming book you read, the first computer science class you took, or the first piece of open source code you saw, method names are typically verbs. Why shouldn’t they be? Methods are ways to encapsulate code that does stuff. But as we work on projects for longer and longer, we get lazier and lazier and our code goes from “register_user_and_email_password()” to “new_account()“.

Obviously, the former is cleaner than the latter, but if we’re striving for quality unit testing and we want to make sure that our unit tests are easy to read and in order for them to be easy to read, our function names must be easy to read.

Isn’t this easier to read:

$this->assertFalse( register_user_and_email_password( '' ) );

Instead of this?

$this->assertFalse( new_account( '' ) );

Again, perhaps this is a simple example, but the principle remains: Writing good unit tests in order to help self-document the code that drives the language of your functions.


Conclusion

We’ve talked about the basics of unit testing as well as the key benefits, but we’ve yet to discuss the disadvantages that come with unit testing and we’ve not even taken a look at how to incorporate it into our workflow.

So in the next article, we’ll attempt to do just that.

Original from: http://wp.tutsplus.com/tutorials/creative-coding/the-theory-of-unit-testing-part-2/

Building WordPress Themes from Scratch: A New Book From One of Our Wptuts+ Authors

June 7th, 2012 Comments off

Today we’re announcing the launch of a new Rockable Press book, Building WordPress Themes from Scratch by our very own Wptuts+ author Joe Casabona!


Some Words From the Author

Hi, I’m Joe, the author of Building WordPress Themes From Scratch, and what started out as a simple, open source blogging platform has now become a super-powerful content management system (CMS) that can boast that it’s the most widely-used CMS on the Internet.

From the moment I first started using WordPress about eight years ago, I fell in love with it straight away and immediately started hacking away at it, learning the platform, making my own changes, and watching it grow over the years.

In this book, I plan to teach you how to use WordPress, as well as how to leverage the API to create your own custom themes, plugins, and content types. In other words, I will show you how to make WordPress your own.


What Does Joe Cover in the Book?

This book reads much like a long, multi-part tutorial, where I take you through my design process, explaining what I do (and why I do it) every step of the way.

Although it’s a fairly linear guide, my hope is that you can visit any main section of the book for quick reference.

So, here’s what I’ll be doing:

  1. Converting HTML/CSS to a Dynamic WordPress Theme

    Included with the book is a PSD that I’ve transformed into HTML. The first part of this book will be taking the resulting HTML/CSS and converting it to a WordPress theme. Along the way, I’ll talk about the various theme pages we’re working with, the WordPress theme hierarchy, and of course, the WordPress Loop.

  2. Creating a Custom Post Type

    This, in my humble opinion, is one of the best additions to WordPress in recent releases. With the ability to make your own content types – each with its own theme template – you can take WordPress from being a CMS only limited to blog posts and pages, to a CMS that can manage any kind of content you can imagine. In this book, we’ll be creating a business listing type, which will allow us to create a business directory.

  3. Theme Options and Widgets

    With WordPress, you can make a theme your own by adding a ‘theme options’ page and custom widgets. In this section, we’ll make it very easy for people who use our themes to add their own customizations without delving into the code or creating a child theme.

  4. Creating a Plugin

    One of the most powerful facets of WordPress is the fact that it’s pluggable. We can add functionality to our installation of WordPress without changing the core WordPress files. There are vast directories of both free and premium plugins available that vastly expand the capabilities of WordPress. In this final section of this book, we will build our own plugin.


Awesome! Where Can We Get a Copy?

The best part is, there are two ways to get the book:

Option 1: You can buy the book from Rockable Press for $19 (or $29 for the paperback)

Option 2: You can buy the book from the Tuts+ Marketplace for $19

We hope you enjoy the book, and if you still need any convincing, check out the sample linked above.

Original from: http://wp.tutsplus.com/articles/news/building-wordpress-themes-from-scratch-a-new-book-from-one-of-our-wptuts-authors/

Sharing the WordPress Love With Non-Image Media Attachments

April 3rd, 2012 Comments off

While WordPress easily displays images attached to your pages and posts (even without an attachment.php file), the other allowed media types (audio, video, document, text, archive, code, interactive) don’t get the same love – save a direct link to the attachment file. But, you don’t have to resort to uploading your audio, video, or other non-image media attachments elsewhere (like YouTube) in order to display them on your WordPress site. Using the default Twenty Eleven theme as an example, I’ll show you WordPress’ built-in functions for sharing the love with non-image media attachments.


How WordPress Handles Attachments by Default

Under the hood, media items are just WordPress posts, therefore, they are displayed according to the WordPress template hierarchy. The template loader does a check to see if the post is an attachment and has an attachment template. If an attachment template does not exist, WordPress will fall back to the single post template or the default index.php template (if the single post template does not exist).


Template Check

In the single post or index.php templates, WordPress themes will likely display the content using the_content. This function has a default filter attached to it – prepend_attachment – that will automatically add an attachment link to the page (using the wp_get_attachment_link function) if it determines that this is an attachment post. However, the arguments used here in the call to wp_get_attachment_link will only provide actual display for image attachments – non-image attachment files only get a direct link to the attachment file. (Where’s the love?) We could potentially display more than just a link for non-image attachments with a simple change of arguments to wp_get_attachment_link, but unfortunately we don’t have a way to change the arguments before the function is called.


Default Image Attachment Display vs. Default Non-Image Attachment Display

So let’s take a look at what we can do to show our non-image attachments some love.


Taking Control of Non-Image Media Attachment Display

Step 1 Determine the File Type

The first thing we’ll do is determine the file type of the attachment. WordPress allows uploading of several file types, found in the get_allowed_mime_types function shown below.


Default Allowed File Types

Although the Media Library admin screen only shows filters for the three default file types, the Edit page for each media item shows the exact file type. The file type is in the MIME format (MIME is a long-standing standard for classifying file types on the Internet) which has two parts: type and subtype separated by the /. In the image below, the type is “video” and the subtype is “mp4.” This knowledge will come in handy for step 2.


Default File Types Shown in Media Library

File Types Shown on Edit Media Page

Built-In WordPress Function

WordPress has a built-in function for determining the file type of an attachment using the attachment post ID.

get_post_mime_type($ID)

This function will return the file type in MIME format, just as it’s shown on the media item’s edit page in the admin.
Now we’re ready to take control of displaying non-image attachments in our theme template files.

Step 2 Create Theme Template File


Template Hierarchy

As shown in the image, the WordPress template hierarchy has four possible attachment templates it will look for after it determines that we are displaying an attachment post. We can either handle the display of each file type in the attachment.php file or we can create separate template files for each MIME type and/or MIME subtype. Let’s take a look at these options.

Option 1. attachment.php File

We can handle the display of each file type in attachment.php using our handy get_post_mime_type function.

First, we’ll get the file type of the attachment (while inside the loop):

ID ); ?>

Then, we can do a switch statement on the file type to provide the code to display each type:


So if we’d like to display audio (mp3) and video (mp4) attachments, our switch statement would look like this:


Using attachment.php is great if you only have a few file types to display (or your display for each file type will follow the same basic layout) as it allows us to keep our code in one file. If we have several file types and/or you plan to customize the display layout for each file type, you’ll want to take a look at option 2.

Option 2. $mimetype.php, $mimesubtype.php, or $mimetype_$mimesubtype.php

attachment.php is actually the fallback template for template files with the name of the MIME type or MIME subtype of the current attachment post. WordPress will look for files with names like $mimetype.php, $mimesubtype.php, or $mimetype_$mimesubtype.php before falling back to attachment.php.

So instead of calling get_post_mime_type and using a switch statement, we can just create a template file with the name of the MIME type or subtype:

  • audio.php
  • mpeg.php
  • audio_mpeg.php

and place the code to display that file type.

Note: The file names are listed in the order in which WordPress will call them. So $mimetype.php first, then fallback to $mimesubtype.php, then fallback to $mimetype_$mimesubtype.php.

Now let’s look at some examples.


Examples

Displaying Documents

I don’t know about you, but I personally dislike having to download a document to my computer just to view it. Let’s enlist the help of the embeddable Google Docs Viewer. It can display PDFs, spreadsheets, presentations and many other file types listed in Google Help. There’s no requirement for your documents to be hosted on Google Docs as it will embed a viewer right in the page by passing it a file URL and setting the embedded parameter to true.

Here’s how we would handle displaying documents using the Google Docs Viewer in attachment.php after getting the file type:

switch( $type ) 
	case 'application/pdf':
	case 'application/msword': ?>
			
	

Or, we could create one of the following template files:

  • application.php
  • pdf.php
  • application_pdf.php

and place the following code where you’d like to display the content inside the loop:

	

Notice that we are passing the URL of the attachment file to the Google Docs viewer using the wp_get_attachment_url function.

Final Result:

Audio

To display (play) audio files uploaded to WordPress and provide a consistent cross-browser experience, we’re going to enlist the help of the lightweight audio.js library that allows us to use the HTML5 audio tag anywhere, falling back to flash in browsers that don’t support HTML5 audio yet.

First, download and place the audio.js files in your theme. Then, in your functions.php file, add the code to enqueue the audio.js javascript on attachment pages only (following best practices). I’m sure there are other ways to do this – including using the recommended wp_enqueue_scripts action and some conditional statements – however, I’m going to illustrate the method in this article: Quick Tip: Including JavaScript and CSS Only On Certain Site Pages

add_filter( 'attachment_template', 'ncb_attachment_template' );

function ncb_attachment_template( $template_path ) 
	wp_enqueue_script( 'audio-js', get_template_directory_uri() . '/js/audiojs/audiojs/audio.min.js' );
	add_action( 'wp_head', 'ncb_audio_js' );

	return $template_path;


function ncb_audio_js() 
	echo '';
}

Then, we can add the following code to our attachment.php file:


	
	

Here’s our full switch statement up to this point:


		
	
		
	

Or, we could create one of the following template files:

  • audio.php
  • mpeg.php
  • audio_mpeg.php

and add our audio code inside the loop where we’d like to display the content:

	

Note: If you use file type template files, the JavaScript needs to be enqueued on those pages only.

Final Result:

Video

We can display (play) video files uploaded to WordPress much the same as audio, except we’re going to enlist the help of the video.js library that allows us to use the HTML5 video tag anywhere, falling back to flash in browsers that don’t support HTML5 video yet.

Just as with audio, we’ll download the files, add them to our theme directory, and enqueue the video.js javascript on attachment pages only, save for the addition of a CSS file:

wp_enqueue_script( 'video-js', get_template_directory_uri() . '/js/video-js/video.min.js' );
wp_enqueue_style( 'video-js-css', get_template_directory_uri() . '/js/video-js/video-js.min.css' );

Here’s the full functions.php snippet:

add_filter( 'attachment_template', 'ncb_attachment_template' );

function ncb_attachment_template( $template_path ) 
	wp_enqueue_script( 'audio-js', get_template_directory_uri() . '/js/audiojs/audiojs/audio.min.js' );
	add_action( 'wp_head', 'ncb_audio_js' );

	wp_enqueue_script( 'video-js', get_template_directory_uri() . '/js/video-js/video.min.js' );
	wp_enqueue_style( 'video-js-css', get_template_directory_uri() . '/js/video-js/video-js.min.css' );

	return $template_path;


function ncb_audio_js() 
	echo '';
}

Then, we can add the following code to our attachment.php file:


		';
	

Here’s our full switch statement:


		
	
		
	
		';

Or, we could create one of the following template files:

  • video.php
  • mp4.php
  • video_mp4.php

and add our video code inside the loop where we’d like to display the content:

	

Remember: When using file type template files instead of attachment.php, you will need to change the name of the filter used to call the function that enqueues your JavaScript.

Final Result:


Summary

Non-image media attachments in WordPress need love, too! Using only two WordPress functions, you can keep your media files on your site and customize the display and layout of any of the allowed file types.

Download and/or fork the working code on Github.

References in This Article

WordPress functions

WordPress template files

  • attachment.php
  • index.php
  • single.php
  • $mimetype.php
  • $mimesubtype.php
  • $mimetype_$mimesubtype.php

Original from: http://wp.tutsplus.com/tutorials/creative-coding/sharing-the-wordpress-love-with-non-image-media-attachments/

A Short Guide to Trackbacks

March 18th, 2012 Comments off

Trackbacks connect blogs together and create a network of blogs in the same way that links create a network of web pages.


Basics and Benefits

A trackback is a notification of linking to a web document. In other words this system allows peer-to-peer communication and conversations between blogs. It helps keep track of who is linking or referring to a webpage (article) and therefore brings interested readers to the given site. Trackback is one of the three linkback methods, the other two being refback and pingback. Note that for applying a trackback it is not necessary to be physically linked with each other. Pingbacks were designed to solve some of the problems that people saw with trackbacks.


Brief Practical Example

  1. Joe writes a new article on his blog and presses the publish button.
  2. Melissa wants to comment on Joe’s blog, but wants her own readers to see what she had to say, and be able to comment on her own blog
  3. Melissa posts on her own blog and sends a trackback to Joe’s site
  4. Joe’s page receives the trackback, and displays it as a comment to the original post. This comment contains a link to Melissa’s post.

History

Trackbacks have been around about as long as blogging. In 2002, the specification for trackbacks was created by Six Apart which first implemented it in Movable Type. Since then it has been implemented in other blogging tools as well. Six Apart started a working group in February 2006 focusing on improvements. Six Apart also has submitted trackback to the Internet Engineering Task Force (IETF) for approval as a standard online protocol. One well known blogging service that does not support trackback is Blogger. Instead they support backlinks.


More Details

Blogging software, like WordPress, Drupal, and Movable Type, support automatic pingbacks. Often the term pingback is used for any kind of linkback. Some other software that support trackbacks are: ExpressionEngine, Sitefinity, Typo, CodeIgniter, and Weebly.

The notification medium of this method is HTTP POST. By default the minimum information sent by the linking server for backing is the linking post URL. Further optional data can be: linking site name, linking post title, and linking post excerpt. The trackback specification describes a REST framework, within which the client makes a standard HTTP call, or ping, and receives an XML response. The ping is automatically generated in some versions of blogging software, though in others a blogger has to manually send the ping. Software that supports the protocol will display a URL at the end of each post (trackback / pingback).


Spam Pirates

Trackback has been targeted by spammers hoping to improve search engine rankings to their own sites by increasing their number of inbound links. Many versions of blogging software have added spam filters, such as CAPTCHAs, to block link abuse.


The WordPress Approach of Trackbacks

Fortunately we don’t need a plugin to display the trackback information because by default WordPress comments will show the trackbacks / pingbacks in line with other comments. Our favourite content management system goes to a new level by allowing pingbacks. Pingbacks allow you to notify a weblog of your entry just by posting its permalink directly in the content of your blog entry. No special trackback link is necessary. To enable pinging URLs in the blog entry, make sure there is a check mark next to “Attempt to notify any Weblogs linked to from the article (slows down posting.)” in the “Options→Discussion” section of the WordPress admin panel.


Usage

You can react / connect with a trackback URL this way: copy that other entry’s trackback URL into your post’s trackback field and publish your post. You may have to turn on the trackback or pingback field to show up on the new entry view in WordPress’ admin.


Manoeuvres

A successful operation usually appears in a couple of seconds after publishing your blog entry, but note that trackbacks and pingbacks can be moderated or disabled. WordPress will display all the URLs that were notified about your blog entry. Sometimes a blog may be having technical difficulties with the trackback or pingback system. If you believe that is the case, you can politely send the blog owner a message outlining the potential problem, be sure to include all necessary and relevant information for them to troubleshoot.


Figuring Out Trackback Support

Usually you can assume that most WordPress blogs support the pingback feature, however, it can be disabled or moderated. If the site has pings enabled, a link with a brief sampling of the text around it will appear on their blog. WordPress uses the file called xmlrpc.php to handle pingbacks. In short it uses XML-RPC, which is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism. If you want to be certain pingbacks are supported, you have to look into the page source (HTML code):



Positive and Negative Technicalities

It is a very good thing that the information needed for requesting (site name, title, and excerpt) are present in the notification itself. But there are some cons as well, for example:

  • notification requires positive action by linking server,
  • the technical specification is only partially designed,
  • source code validation (HTML) may be prevented during autodiscovery,
  • extremely vulnerable to spam.

Requesting

Here is an example sending a standard HTTP GET request to ping the URL.


http://foo.com/mt/mt-tb.cgi?tb_id=ID&title=TITLE&url=URL


XML Responses

Possible successful ping response:



0

A failed ping response can be:



1
The error message


The Power of Pinging: Creative Uses

Trackbacks can be used as a discussion board, but there’s more to it. A very interesting thing you can do with trackbacks is to display the songs played on your mp3 playing application (eg. iTunes, WinAmp). Trackbacks are great to help promote your blog as well, be sure to use them within the same niche or category.


Official Specs

Read the official trackback technical specification at the Movable Type website, or if you prefer the pingback documentation it’s also available on Ian Hickson’s webpage.


Tips On Using Things Wisely

  • WordPress allows you to set your default ping status in the Options menu. If the majority of your posts will have trackbacks (or pingbacks) enabled, setting it to accept them could make your blogging life a little easier. To set it go to the admin panel, then Options → Discussion and check “Allow link notifications from other Weblogs (pingbacks and trackbacks.)”.
  • If the site you’re linking to has pingbacks enabled, be sure not to trackback!
  • If your trackback or pingback doesn’t show up on the website, don’t try to force it by continually using trackback or pingback.
  • To not be considered spam, avoid trackback sending unless you actually reference the site you’re sending the trackback to.

Finally

Don’t just read about trackbacks, apply it in practice! For starters: at least make a post with a trackback! Good luck!

Original from: http://wp.tutsplus.com/articles/general/a-short-guide-to-trackbacks/