Friday, November 19, 2010

Tips on How to Code Web Designs Better

Tips on How to Code Web Designs Better: "

Tips on How to Code Web Designs Better


Writing semantic, efficient and valid HTML and CSS can be a time-intensive process that only gets better with experience. While it is important to take the time to produce high-quality code — as it is what separates professionals from hobbyists — it is equally important to produce websites as expeditiously and efficiently as possible.


As web designers, we’re always looking for ways to be more productive. Getting more work done in less time while at the same time maintaining (or improving) our products’ quality is a lifelong quest for many of us.



This article discusses a few fundamental techniques for writing high quality and efficient HTML and CSS.


Use Templates and Frameworks (Even If It’s Homemade)


Using templates and frameworks provides you with a solid baseline from which to start from. For example, CSS frameworks such as the 960 Grid System and Blueprint can save you time in having to write code for bulletproof web page layouts. The purpose of a framework is to reduce development time by avoiding having to repeatedly write cross-browser-tested code for each of your projects. However, take note: Using frameworks involves a learning curve and can bulk up your web page sizes with unnecessary style rules and markup.


Even something as simple as using this XHTML 1.0 strict template — a skeleton for your HTML documents — can be a time-saver.


XHTML 1.0 strict template


Whether you choose to use a premade framework or not, the notion you should take a note of is just how much code you end up writing over and over again. It’s imperative to discover these repetitive tasks so that you can come up with a system (a custom template/framework) to help you speed up your workflow.


Conform to XHTML 1.0 Strict Doctype


Writing under the Strict doctype forces you to produce smarter and specifications-conformant code. Strict doctype lowers your desire to use hacks, deprecated elements, proprietary code, and unconventional markup that in the future will give you grief and maintenance costs related to debugging and updating projects.


Conform to XHTML 1.0 Strict Doctype


Strict doctype also instructs web browsers to render your web pages under strict W3C specifications, which can reduce browser-specific bugs and thus lowering your development time.


Use Good and Consistent Naming Conventions


Always use consistent naming conventions for easier organization and so that you can produce work that is meaningful and expressive.


For example, if you use hyphens (-) to separate words in your classes and IDs (e.g. sidebar-blurb, about-us), don’t use underscores (_) for others (e.g. footer_nav, header_logo). Also, using standard and meaningful filenames for documents and directories is a good practice to get into.


Here are some popular classes, IDs and file names:



  • Structural IDs: #header, #footer, #sidebar, #content, #wrapper, #container

  • Main stylesheet: style.css, styles.css, global.css

  • Main JavaScript library: javascript.js, scripts.js

  • JavaScript directory: js, javascript or scripts

  • Image directory: images, img

  • CSS directory: css, stylesheets, styles


Naming Conventions


Always use meaningful words for your IDs and classes. For example, using left-col and right-col for div ID attribute values isn’t good because they rely on positional factors rather than semantics. Using something that has greater semantic value such as main-content or aside would be better so that you are giving your layout elements improved meaning and greater flexibility towards changes in the future.


In HTML5, the issue of proper naming conventions and uniformity for layout elements has been addressed with the introduction of new HTML elements such as <nav>, <footer> and <article>, but the concept of using proper naming conventions applies to all HTML elements with ID/class attributes, not just layout elements.


Read more about naming conventions in this article called Structural Naming Convention in CSS.


Good naming conventions are just a best practice in general, but as a bonus, it can help you speed up your development process because of organized and intuitive code, which makes finding and editing things quicker.


Understand and Take Advantage of CSS Inheritance


Instead of assigning every single element a font, color, background, etc., try to take advantage of CSS inheritance rules, especially for fonts, padding and margins. This can reduce the amount of code you have to write and maintain.


For example, the following is terser:


html, body {
background: #eee;
font: normal 11pt/14pt Arial, Helvetica, sans-serif;
color: #000;
}
ul, ol {
font-size: 18pt;
}

Compared to:


html, body {
background: #eee;
}
p {
font: normal 11pt/14pt Arial, Helvetica, sans-serif;
color: #000;
}
ul, ol {
font: normal 11pt/18pt Arial, Helvetica, sans-serif;
color: #000;
}
blockquote {
font: normal 11pt/14pt Arial, Helvetica, sans-serif;
color: #000;
}

Reset Your Style Rules


One of the biggest time-sinks in web design is debugging browser-specific bugs. In order to ensure that you start off with a solid baseline — and thus avoid differences across web browsers — consider resetting your CSS. Read more about this subject in the article called Resetting Your Styles with CSS Reset.


Just like using CSS frameworks and HTML starter templates, there are several CSS reset templates that you can take advantage of. Here is a couple:



Here is Eric Meyer’s Reset CSS:



/* v1.0 | 20080212 */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}

/* remember to define focus styles! */
:focus {
outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}

/* tables still need 'cellspacing='0'' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}

The best practice for using CSS reset templates is to fill in the property values of "resetted" styles instead of re-declaring them again.


For example, in Eric Meyer’s Reset CSS shown above, the line-height of web pages on the site is set to 1. If you know that your line-height needs to be 1.5, then you should change 1 to 1.5.


Do not do this when using CSS reset templates:



/ * Not good */
body {
line-height: 1;
}
...
body { line-height: 1.5; }

In addition, it’s best to avoid resetting CSS properties using the universal selector (e.g. * { margin: 0; padding: 0; }) because, performance-wise, it is inefficient and can be resource-taxing on older computers. Read more about using efficient CSS selectors.


Use CSS Shorthand Properties


Writing less CSS means saving time. Not only does using shorthand CSS reduce code-writing, but it also lowers the file sizes of your stylesheets, which ultimately means faster page response times. Additionally, shorthand CSS makes your code cleaner and — albeit arguably depending on your preference — easier to read and maintain.


The following are some popular shorthand syntax to memorize and use, with the longhand syntax equivalent preceding it.


Margin and Padding Properties


/* Longhand */
margin-top: 0;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 15px;
padding-top: 0px;
padding-right: 20px;
padding-bottom: 0px;
padding-left: 20px;

/* Shorthand */
margin: 0 20px 10px 15px;
padding: 15px 20px 0;

A quick guide:



  • When 4 property values are used – margin/padding: [top | right | bottom | left]

  • When 3 property values are used – margin/padding: [top | left and right | bottom]

  • When 2 property values are used – margin/padding: [top and bottom | left and right]

  • When 1 property value is used – margin/padding: [top, right, bottom, and left ]


Font Properties


/* Longhand */
font-style: normal;
line-height: 11px;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;

/* Shorthand */
font: normal 18px/11px Arial, Helvetica, sans-serif;

A quick guide:



  • font: [font-style | font-size/line-height | font-family];


Background Properties


/* Longhand */
background-color: #ffffff;
background-image: url('../images/background.jpg');
background-repeat: repeat-x;
background-position: top center;

/* Shorthand */
background: #fff url('../images/background.jpg') repeat-x top center;

A quick guide:



  • background: [background-color | background-image:url() | background-repeat | background-position];


To discover more shorthand CSS syntax, take a look at the CSS Shorthand Guide.


Put Things in the Proper Place and Order


Always put things in the conventional place, i.e., where best practices and W3C specifications say they should go. For example, it is best practice to reference external JavaScript libraries after external stylesheet references to improve page responsiveness and to take advantage of the nature of parallel downloading.


This is the best way:


<head>
<!-- CSS on top, JavaScript after -->
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="script.js" />
</head>

The suboptimal way:


<head>
<!-- CSS at the bottom, JavaScript on top -->
<script type="text/javascript" src="script.js" />
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>

Note that both code blocks above are valid under specs, but one is better than the other.


When writing structural markup, think in terms of top to bottom and left to right because that’s the accepted convention. If a sidebar is to the right of a content area and below a header, then the markup should be organized as follows:


<div id="header">
</div>
<div id="content">
</div>
<div id="sidebar">
</div>

However, if the sidebar is on the left, a better practice would be to organize markup like this:


<div id="header">
</div>
<div id="sidebar">
</div>
<div id="content">
</div>

A caveat to the above is when you are optimizing your work for screen readers. The second code block above means that screen readers will always encounter the secondary content (#sidebar) before the main content (#content), which can hamper the reading of people that require screen-reading assistive technologies. In this case, you could place #sidebar lower down the document and use CSS for visual positioning (i.e. float #sidebar to the left, float #content to the right).


In addition to putting HTML elements in their respective places, it’s also important to organize CSS (again, for easier maintenance and readability). In a way, it should mimic the organization of your markup. For example, the #header styles should be before the #footer styles. This is a matter of preference, but it is also a conventional way of organizing style rules.


/* Structural Styles */
#header {
// header properties
}
#header .logo {
//site's logo properties
}
#footer {
// footer properties
}

Conclusion


As in most things, the way to better and more efficient coding is to work smarter, not harder. The tips discussed in this article are basic; however, it might also inspire you to delve deeper into these sorts of optimizations and enhancements for improving the craftsmanship of the things you make.


What are your own tips and techniques for better and more efficient coding?


Related Content



About the Author


Kayla Knight is a web designer and web developer who loves coding way too much for her own good. She does freelance design/development work and helps run the XHTML Shop. Connect with her by visiting her website and following her on Twitter @ KaylaMaeKnight.




"

Facebook’s Efforts in Japan, South Korea and Russia Show New Localization Focus

Facebook’s Efforts in Japan, South Korea and Russia Show New Localization Focus: "

For most of its history, Facebook has tried to build a single product that works for everyone in the world. The only localization it offered was the text on the site, and even that was a one-size-fits-all product — its Translation tool allowed it to quickly launch in new languages using feedback from users.


But now, we’re seeing more signs of Facebook trying to customize its products for specific locations, at least for a few major markets where it wants to grow. Some of the latest examples are a new game-style Facebook site tour for new Japanese users, and a small engineering expansion in South Korea. We’ll look at these and more, below.


Certain Countries Get Special Attention


The stage has already been set for product localization. Company chief executive Mark Zuckerberg said in October that four countries had become targets for new growth over the past year: South Korea, Japan, China and Russia. Aside from all being located at least partly in Asia, these four companies are also notable because they all have well-established local social networking competitors: Vkontakte in Russia, Cyworld in Korea, Mixi in Japan and Tencent among others in China. More generally, all of these countries have unique languages, cultures, and in some cases government regulations that have historically hindered outside competitors.


Out of those four, Facebook is blocked in China — the company has hinted that it might work with the government in order to be allowed in, but that hasn’t happened yet. So here’s a look at what’s happening with Facebook in the other three locations. All data is from our Global Monitor report, part of our Inside Facebook Gold subscription service. Note for subscribers: We’ll be coming out with a detailed new monthly report analyzing worldwide Facebook traffic and trends, with the first one arriving in early December.


Japan


Facebook’s first foreign engineering office opened in Tokyo, Japan, this past year. So far, it has introduced products like a customized interface for mobile users, and an in-house app designed to help users with job searches. That app, the first Facebook has made for a local market, is most interesting for its cultural focus — it is intended as a way for users to make connections in the traditionally rigid Japanese job market.



It also introduced a way to syndicate Facebook content to Mixi accounts.


The most recent example of Japanese localization is from a couple weeks ago, when Facebook added a new site tour that prompts users to take a set of four “missions.” The missions are just a series of screenshots and text explaining how people can fill out their profiles, and include tips aimed at Japanese users (like talking about the value of using real-world names). This sort of site tour page doesn’t currently exist in other languages that we know of, which is reflected in the Japanese page’s generic Facebook URL.


Japan’s growth began picking up around the middle of 2009, after the first translated version of the site became available. Since then, it has lagged much of the rest of Asia in the world. But it’s continued to steadily climb, and had its highest numbers yet in October, with 1.69 million monthly active users and 262,000 new ones.


South Korea


Facebook isn’t saying much about what it’s doing in the country. The two previous postings about contract sales engineering positions are no longer on the Careers page, but there’s a new posting for a full-time sales engineering position. Besides the job listings, the most prominent thing the company has done was launch a dedicated page about the country.



We’ve heard it could be expanding its local engineering operations beyond sales, but a spokesperson’s response seems to shoot that down. “We are currently only hiring for jobs that are posted on the Careers page, and don’t have much more to say on rumors and speculation.” The expansion, in whatever form it might be taking, has not yet resulted in any Korea-focused Facebook products.


Yet, after a first year or so of slow growth, the country’s Facebook base has quadrupled since April, passing Japan to reach 267,000 new users and 1.73 million total MAU by October. Facebook, as Zuckerberg suggested, has even bigger ambitions.


Russia


The last difficult-but-winnable country on the list is Russia, where the social network faces a number of homegrown rivals. Facebook shares an investor, Digital Sky Technologies, with a few of these including Vkontakte. So far, the company has done a couple 0.facebook.com mobile integration deals so mobile users with some local carriers can get free access to the site, for example. But the ’0′ deals aren’t particularly special, since the company has done dozens of those deals around the world.


Facebook started making Russia-specific moves a few weeks ago, when leading Russian search engine company Yandex began tightly integrating Facebook content in a special deal similar to what Facebook is doing with Microsoft’s Bing search engine (but not with Google).


Russia, like the previous two countries, is seeing a distinct growth surge. It grew by 548,000 last month to reach 2.132 million MAU — a striking increase given its slower history, and local competition.


What the Future Holds


These examples are new and mostly basic, but we expect the localization efforts to increase as Facebook looks to strengthen its market position around the world. Beyond more guides and other content, it will likely try to use its products to benefit key local partners , as with the case with Yandex, or to help solve relevant market problems, as is the case with the Japan job search app.


Stay tuned for more detailed coverage of Facebook around the world in our Inside Facebook Gold data and analysis service.


"

How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

How To Use the “Seven Deadly Sins” to Turn Visitors into Customers: "
Advertisement in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers
 in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers  in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers  in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Since the beginning of time, people have exploited the human desire to sin so that they could achieve their goals. Finding out what causes people to sin helps us understand the triggers which prompt people to take an action. The Web has made it even easier to exploit these tendencies to sin, in order to build user engagement and excitement about your service or product. In this article we’ll show examples of how successful companies exploit the tendency to conduct all the famous Seven Deadly Sins, and in turn generate momentum with their website visitors. Ready? Let’s roll.

Sin #1: Pride

Pride is defined as having an excessively high opinion of oneself. You must remember someone from your school days who had an extremely high sense of their personal appearance or abilities. That’s pride at work. On the Web, this sin will help you sell your product. Every website visitor wants to be associated with a successful service that other people might find impressive.

People want to say: “Yes, Fortune 500 companies use this tool and I use it as well,” or “Yes, I got on the homepage of Dribbble in front of thousands of other designers; that’s the type of work I do.” In all these examples, people are proud of their achievements and the website helps them show their pride. Here are examples of this first sin in action:

Showing off your customers. People want to use tools that big brands use. SEOmoz does a great job of fronting up the logos of famous companies that pay for their tools, with a simple call to action prompting you to be as successful as these top brands. This entices users to try this tool: “I want to use something big brands use.”

Prideseomoz in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

Fronting up the top users. People want to be considered the best. You are proud to be nominated or picked to be the best. You brag about it to your friends. You mention your accomplishments to your significant other. You want to to be picked as the best one, over thousands of others. Dribbble fronts up top designs on their homepage. This forces people to use their website more and more, to get to the top. A little pride on your site just might get many more customers to use your service.

Dribble in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

Sin #2: Gluttony

Most people think of gluttony in terms of eating. However, the more generic definition of this sin is over-consuming something to the point that it is wasted. It’s a desire to consume more than you can possibly consume. On the Web, companies use this sin to seduce the user into signing up by promising an endless supply of goods.

How many times have you seen “Unlimited” as one of the motivators to get you to buy a tool or service? We are a consumer generation. We want more and more awesome functionality and coolness for our money. The more a website promises us for our money, the more likely you are to sign up. Here are examples of this sin in action:

Glut-flickr in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

The unlimited gluttony of features for a cheap price drives people to sign up for a product or service. If you want to attract user’s attention, create a valuable offer and provide unlimited resources for customers to use or collect.

Glut-survey in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

Sin #3: Sloth

In the modern view, “sloth” means laziness and indifference. Let’s face it, some of us are extremely lazy by nature. If we don’t have to do something, we’d rather not do it. On the Web, this sin is seen as making tasks overly simple and easy for potential customers. Products and services which “do all the hard work for you” win customers over. Here are some examples of this technique in action:

Making posting a blog post ridiculously easy from anywhere. Posterous is another example of sloth. Don’t want to invest too much time in a blog post? Want to just email or text message your blog post to post it? Solved. Now you don’t have to worry about the formatting, the look and feel, or any other details. You just email the text for your blogs and Posterous takes care of all the details.

Making finances ridiculously easy. Mint is a great example of sloth. Who really wants to spend their time looking for the best interest rates for their savings accounts? Who wants to track their spending? All I have to do is give Mint my financial details and it will tell me where I’m overspending, and also look through thousands of banks to give me the best deals. The tagline reads: “We download and categorize your balances and transactions automatically every day—making it effortless to see graphs of your spending, income, balances, and net worth.” I could do all this on my own, but I’m lazy, and I want someone else to do this for me.

Sin #4: Envy

Envy is when you want something others have. You’re so envious of people that have a status or possession you want, that you’re willing to do what ever it takes to get. On the Web you see this in envy for reward points, followers, friends, and private invites. Here are examples of this in action:

Achieving a status. Mayorship in Foursquare is a great example of this. Ever hear something like this from someone you know: “Who has the mayorship of the Starbucks I go to? Oh, he has only 35 check-ins. I’ll totally beat him next week.” People want that “mayor” status. They’re envious of the person that has it. This drives people to use Foursquare more and more to achieve that status.

Envy-four in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

Rockmelt is a web browser that can be downloaded only per invite. The developers portray the browser as “your browser, re-imagined.” They ask folks who want to join, to connect via Facebook and request an invite. Once you’ve done it, your friends on Facebook who already use Rockmelt can see that you asked for an invite and send you one through the browser’s interface.

Rockmelt in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

You might also check up on whether existing members share invite codes on Twitter. This exclusivity creates envy in people who don’t have invites. This envy fuels their desire to constantly seek an invite to Rockmelt, all the time. Once you actually become a user of the tool, you feel like you’re part of an exclusive club and are strongly encouraged to engage with the tool.

Give people something to envy on your website, and you’ll see more loyal users engaging with your service or product.

Sin #5: Lust

Lust is usually thought of as excessive sexual desire. On the Web, this sin translates into our desire to buy sexy, shiny things which not all of us can afford. Websites use interactivity with large, bold, rotating images to seduce us into buying the gadget. Here is an example of lust in action:

Providing the ability to play around and view the product. In web design, lust is often triggered by professional product photography which appears shining, attractive and exclusive in its own right. Rolex’s website is an example of this. The sliding gallery encourages the site visitors to explore the site which is not just a showcase of Rolex’s products, but rather an exhibition of company’s image, style, philosophy and branding.

Rolex in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Rolex tells the story about the quality of its products, their precision and aesthetic appeal. Notice how the designers provide animations and various views for each product, making it more interesting and desireable.

Volkswagen does a good job of seducing people into buying their cars. Its interactive website lets you customize and build your own version of the car you’re interested in. It is even possible to paint the car in whichever color you like. The process of pimping your car in the way you want, makes you lust over the car you’ve just “created.” In this example, our lust for shiny things is exploited. The more we interact with the Volkswagen website, the more we want to buy their product.

Vwlust1 in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

Sin #6: Greed

Greed is an overly excessive pursuit of status, power and wealth. It’s the desire to have more than you need or deserve. The pursuit is so strong that one would go through any means necessary to fulfill it. On the Web, this sin is seen in the desire to gain influence, followers and power.

Being hungry for more Twitter followers. Twitter is the perfect example of a website where all of us are hungry for more followers. The famous wars of Ashton Kutcher, Oprah, CNN and Britney Spears for more followers, shows us how greed gets the best of us. The more followers we have, the more influence we have over people. All of us are greedy for these followers.

Getting power through more Digg followers. The original model behind Digg was very simple: you “digg” a specific piece of news, or a website. Your friends see this, and “digg” this same article, moving it to the top. The top articles on the Digg homepage get millions of people checking them out. The more friends you have, the easier it is for you to move any news to the top. A person who has 500,000 friends can move a story to the top of Digg in minutes, as opposed to someone who is just starting out. People at the top have much more power over everyone else. The greed for friends on Digg is what keeps us hungry for more.

In these examples above, we are hungry to gain influence and power and want to engage with the service to fulfill our goal.

Sin #7: Wrath

Last but not least, wrath is defined as uncontrolled feelings of rage, anger and hatred. On the Web, this sin is used by companies to generate gossip and buzz around their product or service.

Encouraging criticism. Amazon is a perfect example of using wrath to create controversy and more engagement with the product. The website fronts up the most helpful critical review, right beside the most helpful, favorable review. This prompts the shoppers to respond to these reviews and to add their own reviews, as they try the product out.

Amazonwrath in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Full Interactive View | Summary view

Catering to frustration. The Consumerist is a perfect example of using consumer frustration to generate content and activity on a website. Giving angry shoppers the ability to vent and to express their frustrations, generates tremendously long discussions and activity on the website. The concept of consumer anger is rooted deep in the Consumerist tagline:

Consumerist in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Furthermore, as you use the website and vent your anger about products, you get even more worked up about banners such as these (found on the Consumerist website):

Wrath-Consumerist-2 in How To Use the “Seven Deadly Sins” to Turn Visitors into Customers

Conclusion

You can now see in what way the results sinning on the Web generate for your business. Keep in mind that when companies try to get their customers to sin too hard, it’s usually very apparent and often results in drawing potential customers away. It’s important to maintain a good balance between sin and common sense. Next time you’re creating a website for a product or service, think back to these examples of the Seven Deadly Sins in action and see how you can use them to your advantage. Now go out there and get your customers to sin. What are you waiting for?

(ik)(vf)


© ZURB for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , , , , , , , , ,

"

Beginning WordPress Development: A Look at Common Functions

Beginning WordPress Development: A Look at Common Functions: "

Beginning WordPress Development: A Look at Common Functions


WordPress is a great blogging and CMS platform. It’s easy to use and customize, and there’s basically nothing you can’t do with it. If you haven’t used WordPress, give it a try by installing it on your own computer using a web server package like xampp or WampServer. You’ll need access to WordPress in order to follow along with this guide.


In this guide, we will take a look at some common functions in WordPress for use in custom WordPress theme development.



Introduction


As a developer, one of my favorite things about WordPress is its built-in functions, which allow you to easily manipulate and extend WordPress with just a few lines of code.


WordPress functions are an essential component of WordPress theme development; once you understand how they work, it’s easy to create your own custom WordPress themes.


Navigation


The most popular sets of functions in WordPress are navigation-related functions. For navigation menus, a popular function for dynamically generating them is to use the wp_list_pages WordPress function. Another method for dealing with site navigation was recently introduced in WordPress 3.0: the wp_nav_menu function.


We’ll talk about these two functions, starting with wp_list_pages.


Listing All Pages


If you want to list all of the pages you’ve got (note that pages and posts have different meanings in WordPress vernacular), there’s a simple function for that called wp_list_pages. When used without any parameters, it will list all of your pages in alphabetical order.



<?php wp_list_pages(); ?>

Listing Specific Pages


As with many WordPress functions, the wp_list_pages function takes several parameters. For example, the include parameter allows you to list specific pages by referencing their page IDs, separated by commas (,). The following example will only list two pages (the pages have IDs of 4 and 5).



<?php wp_list_pages('include=4,5'); ?>

Excluding Specific Pages from a List


You can also exclude specific pages using the exclude parameter:



<?php wp_list_pages('exclude=4,5'); ?>

Sorting Pages


As discussed earlier, the default sorting order of wp_list_pages is alphabetical. You can, however, change the order of the listing using the sort_column parameter. The sort_column parameter can have 1 of 7 values:



  • post_title – Sort alphabetically (default value)

  • menu_order – Sort by page order

  • post_date – Sort by date of creation

  • post_modified – Sort by time last modified

  • ID – Sort by page ID

  • post_author – Sort by the page author ID

  • post_name – Sort alphabetically by post slug


Here is the code for sorting by creation date instead of the default alphabetical order:


<?php wp_list_pages('sort_column=post_date'); ?>

Specifying the Depth


Pages can have subpages, and subpages can have subpages. What if you only wanted to list top-level pages but exclude their subpages? Controlling the depth works great when using it to generate dropdown menus with submenus.


You can use the depth parameter like so:



<?php wp_list_pages('depth=1'); ?>

Enabling WordPress 3.0’s Navigation Menu Feature


If you’re wanting absolute control over your navigation, using WordPress 3.0’s new menu function, wp_nav_menu, is the way to go. With this function, you can add categories in menus, submenus and even insert external links into navigation menus.


To take advantage of the built-in navigation menu functionality, first you need to enable it in your theme. In your functions.php file located in the theme directory, you’ll need to add the following:



<?php add_theme_support( 'menus' ); ?>

Next, place the following code in the location where you want the menu to show on your site (this could be in your standard theme template files such as header.php or single.php):



<?php wp_nav_menu( array('menu' => '[Menu Name]' )); ?>

Replace [Menu Name] with what you want your menu to be named.


You’ll then need to navigate to Appearance > Menus and create your menu with the same exact name. Everything from there is simply drag and drop!


Displaying Blog Information


We’re moving on to getting and working with information about the blog. WordPress has a function for getting and printing your WordPress blog information called bloginfo. This is a good function to use for themes that will be used in multiple domains. There are many parameters you can use for bloginfo; to find all of them, read the bloginfo WordPress Codex documentation.


Getting the Site’s URL


Let’s say your site’s URL is http://example.com. If you want to print this out in the source, you can use the url parameter.



<?php bloginfo('url'); ?>

This works great for absolute link references. For example, if you wanted to reference your logo (let’s say the file name is logo.png) that is in a directory called images, you would do the following:



<img src="<?php bloginfo('url'); ?>/images/logo.png" />

The above outputs:



<img src=" http://example.com/images/logo.png" />

Getting the URL to the Current Theme


To grab the current theme directory’s URL, you can use the template_url parameter. This makes your WordPress themes more flexible so that when you change the domain name or use it in multiple domain names you don’t have to worry about changing anything that references the theme’s location. You can use this parameter a number of ways, such as for referencing custom external stylesheets, images, and JavaScript libraries that are inside the theme directory.



<?php bloginfo('template_url'); ?>

Getting the URL of Your RSS Feed


The bloginfo function can also be used for getting other URLs. For example, if you want to grab the RSS feed URL for your site, you can use the 'rss2_url' parameter:



<?php bloginfo('rss2_url'); ?>

If you wanted to create a link to your RSS feed, you could use the following:



<a href="<?php bloginfo('rss2_url'); ?>">Link to RSS feed</a>

Working with Content


The WordPress loop is used to display your posts. A basic loop looks like this:


<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><?php endwhile; endif; ?>

Not much to look at right now, but it’s what’s going to go inside the loop that really matters.


Querying Posts


First, let’s look at the most important function that goes inside the loop called query_posts. query_posts only needs to be used if you want to display information from another page, post or category than the one the user is currently on. For example, on the front page (controlled by index.php, home.php, or front-page.php theme template files) you could use query_posts to show the three newest posts in the hypothetical category called Featured.


You use query_posts not only to show different kinds of content, but how much content matches the query as well.


Displaying Posts in a Category


Keeping with our Featured category example above, here’s how we’d show the three newest posts from the Featured category:



<?php query_posts('category_name=Featured&posts_per_page=3'); ?>

Aside: Passing Multiple Parameters into Functions


Notice that we passed two parameters into the query_post function. The parameters we passed were category_name and post_per_page.


In functions with more than one parameter, you can pass multiple parameters all at once by separating them with an ampersand (&). You can pass as many parameters as you want. Doing so allows you to increase the specificity of your desired outputs.


Excluding Posts


Similar to wp_list_pages, query_posts has a way to exclude items from being displayed. To do so, you just place a minus character (-) in front of the ID of the items you want to exclude.


For example, let’s say you would like to list all posts except posts from two categories with category IDs of 97 and 34. You could use the cat parameter (which is typically used to display only posts within certain categories) for query_posts:



<?php query_posts('cat=-97,-34'); ?>

Displaying Common Information


Now let’s move on to some more functions we can use inside the loop. Many of these functions can only be used inside the loop and may not work if used outside of it.


Display the title of the post:



<?php the_title(); ?>

Display the URL of the post:



<?php the_permalink(); ?>

Display the content of the post:



<?php the_content(); ?>

Display the excerpt of the post:



<?php the_excerpt(); ?>

Display the category of the post:



<?php the_category(); ?>

Display the tags used in the post:



<?php the_tags(); ?>

Display the time the post was published (uses PHP date formatting as a parameter):



<?php the_time(); ?>

Working with Custom Fields


One of the most powerful functions that WordPress has that seems to take developers a long time to learn is the use of custom fields. Custom fields allow users to add custom name/value pairs typically used for post metadata. For example, users can add a post_thumbnail_url key that has a URL value pointing to the thumbnail image.


Users can add custom fields while they are creating posts and pages in Posts > Add new or Pages > Add new.


Working with Custom Fields


I’ve used custom fields for everything — from post thumbnails and changing the background of the individual post to adding custom link and layout areas. It becomes very powerful once you’ve learned it properly.


Getting custom fields can be done from inside or outside of the loop. If you use it outside the loop, you have to reference the ID of the post or page you want the custom field name/value pair from.


Using Custom Fields to Display Image Thumbnails


Let’s say you want to display an image thumbnail in a post.


First, you must create a new post (Posts > Add new). Under the Custom Fields fieldset, type Thumbnail into the Name field and a URI for the Value field. Then publish the post.


Wherever in the loop you want the URI to be displayed, simply use the echo statement to output the result of get_post_meta (which is a function for getting custom fields).



<?php echo get_post_meta($post->ID, 'Thumbnail', true); ?>

To use get_post_meta outside the loop, change $post->ID to the ID of the post. For example, here’s how to print the URI of the thumbnail image for the post with ID of 6.



<?php echo get_post_meta(6, 'Thumbnail', true); ?>

Since we want to display an image, what we actually need to do is use the echo statement inside the src attribute of an img element:



<img src="<?php echo get_post_meta(6, 'Thumbnail', true); ?>" />

The code from above should output the following:


<img src="/images/thumbnail.jpg" />

Related Content



About the Author


Amber Weinberg is a freelancer with over 10 years of experience. She’s the founder of codesnipp.it, a social site for developers. She specializes in clean, semantic and valid 1.0 Strict XHTML, CSS and WordPress development. She also writes a web development blog on her portfolio site at www.amberweinberg.com.




"

8 Likely Facebook-MySpace Partnership Announcements That I Just Made Up

8 Likely Facebook-MySpace Partnership Announcements That I Just Made Up:

Facebook and MySpace have called a web-presser later today to make a surprise joint announcement that has many Internet insiders scratching their heads.


We could just wait a few hours to find out what this is all about, but there are a lot of page views in pointless speculation, and since a few of my extreme rock-climbing buds happen to be major players behind the scenes of this deal, here are 8 scenarios I just made up that might explain who is eating who’s lunch, and what the rival social networks will probably announce later.


1. MySpace and Facebook have made a bilateral agreement to TAKE FRIENDSTER DOWN.


2. Facebook will announce that they have officially bought the rights to fill in the blank of My_____’s new logo with: “FriendsAreAllOnFacebook”.


3. Facebook’s new Non-Email Email Thingy will offer users the option to Blingee their Messages, which will be powered by MySpace.


4. MySpace is actually just going to become a Farmville-like game within Facebook where players will do their best to build a successful social network without running it into the ground via bad business partnerships and Hollywood excess.



5. Facebook will suggest that MySpace become a fan of not being such a digital landfill for human garbage. MySpace will then ‘poke’ Facebook because they have no idea how the Internet works.


6. Facebook will shock the world by handing over control of their company to MySpace, followed shortly by MySpace posting a bulletin about the time they saw Facebook murder someone.


7. The two networks felt it necessary to use their combined reach and influence to make sure everyone hears the unforgettable news about the The Beatles’ music finally being available on the Internet!


8. There is no actual announcement. This presser is just an elaborately orchestrated opportunity for Facebook representatives to berate and degrade the submissive MySpace delegates in a humiliating display of public dominance.

Thursday, November 18, 2010

Facebook Connect Appears as Sign-Up Option in MySpace Redesign

Facebook Connect Appears as Sign-Up Option in MySpace Redesign: "

As part of its big new site redesign, MySpace has introduced a new Facebook integration that is supposed to let you sign up for MySpace using Facebook Connect. The feature isn’t currently working — you click on the Login with Facebook button, give MySpace extended permissions to access Facebook data, and then nothing happens. But the fact that Connect is here is the latest sign of the News Corp. company’s self-described move away from being a social network to being an entertainment site that relies on its multiple social networks to engage users.


Sources told us last fall that we should expect to see Facebook “everywhere” on MySpace this year, and until now that hadn’t really happened. There was a video application made by a partner in the UK back in January, that happened to use Connect. More significantly, MySpace began letting its users syndicate their status updates to Facebook at the end of this past August — that integration has led to 66,472 daily active users and 490,000 monthly active users as of today, according to our AppData tracking service.



The Facebook Connect option is currently buried off the main page, within the “Sign up” page; you’ll see it on the right-hand side once you click through.



The details of what we’re seeing: Once you enter your Facebook login information and allow MySpace permission to your data anytime, your email, etc., you don’t seem to be logged into MySpace. We tried different browsers — Chrome, Firefox, Safari — to no avail. Facebook Connecting on MySpace.com logs you into Facebook, but not MySpace, and you still have to manually log into MySpace.


We’ll update this article with more details once the feature works.


"

In-Depth Review: Facebook’s New Message Inbox Product

In-Depth Review: Facebook’s New Message Inbox Product: "

Yesterday, Facebook launched its new Messages product, allowing users to see their communication with someone over email, Facebook Messages, Facebook Chat, instant messages, and SMS in the same thread. Facebook automatically delivers messages where it thinks a user is most likely to see them, creates a unified history of the messages, and filters the threads by relationship with the sender to create a Social Inbox.


Here’s a closer look at exactly how the new Messages product works:


Setting Up Messages


Facebook will be rolling out access to the new features over the next several months. Members of the press have been set up with accounts, and can invite two friends each using the multi-friend selector. These invites are not delivered immediately, though, and instead put the recipient near the top of the queue for the roll out.



When a user gains access to the new Messages product, they’ll see a prompt at the top of their home page. From there, they’re directed to claim their new [public username]@facebook.com email address. Emails from friends and friends of friends are routed to their primary Messages folder, while emails from other senders are filtered into the Other Messages folder. Users can still change their privacy settings to prevent non-friends from sending them messages. Emails from anyone who isn’t authorized by this settings are not delivered, and no bounce message is returned.


Next, users are asked to connect their mobile phone to their Facebook account “so friends can use Messages to send you texts”. In the same way that users have activated Facebook for mobile through Account Settings, users get a confirmation code texted to them, which they enter online to confirm their phone number. Lastly, users are asked to go online through Facebook Chat to receive Messages over this medium as well.


The Social Inbox


Once set up, users will see that they now have two folders. The “Messages” folder defaults to hold all of a user’s Messages with friends or friends of friends. “Other Messages” holds Messages with those who aren’t connected to a user, Page updates, Event messages, and messages from old groups. When a user has new Messages, they’ll see counters next to the Messages navigation links in the Facebook home page’s left sidebar.


Users can move conversations between folders to increase or decrease their visibility. Messages from friends of friends display how a user is connected to the sender.


Each thread has a radio button next to it allowing users to toggle it between read and unread. Within each thread, the medium from which a Message was sent is denoted with icons for email or chat. At the bottom of the inbox, users see options to view their Archive or Junk, to which Messages can be assigned to reduce clutter. Users also have the option to permanently delete conversations.


Sending and Receiving Messages


When a user sends a Message, Facebook processes several signals to determine which medium to route it to. If the recipient is actively online on Facebook they’ll receive the Message as a Chat. If the Message is a reply to an email, it will be sent to email. Users can check a box next to the reply field to purposefully send a text message. Regardless of the delivery medium, all Messages appear in the inbox in a thread with the recipient, creating a history of the conversation. This is the first time Facebook has offered users a record of their Facebook Chat, and this functionality could pull users away from GChat, which many people use for its instant message log.



If a user opens a Facebook Chat, the last few Messages from the thread are displayed in the Chat window for context. When users receive email from Messages, the previous few Messages in the thread are included with the new Message.



When replying to a Message, users can toggle a checkbox to use Quick Reply mode, in which hitting ENTER sends the reply, similar to instant messaging. Facebook has integrated user requests for a forward button, allowing users to add people to conversations. Users can upload multiple attachments, including photos, or take a single photo with their webcam. Users must download attachments to view them, unless they are Microsoft Office documents, such as .doc or .xls files, in which case users can follow a link to Office.com where they can see a preview.



How Messages Will Change Communication


The new Messages product will not immediately disrupt the institution of email. Information which only comes in that medium, and which rarely requires interaction a human, such as bank statements or newsletters, is best kept within one’s email inbox. Exchanges in which users share lots of attachments, especially in formats other than Microsoft Office’s, will benefit from in-line previews and mass downloading offered by established email services.


Over time, however, social conversations may be pulled into Facebook. If a conversation naturally occurs across mobile, synchronous, and asynchronous mediums, such as day-to-day exchanges with a friend, using a system which automatically optimizes for immediacy will make the exchange easier. Once part of a conversation occurs through Facebook Chat or private messages, email and text messages will soon feed back to the Social Inbox. Having a centralized, persistent record of the distributed conversation will also make Messages useful for organizing groups, perhaps better than Facebook’s Groups product which doesn’t encompass SMS or record Group Chat.


While the aggregation of additional mediums is useful, Facebook has also solved the biggest problem with its old Messages product. By filtering Messages according the user’s relationship with the sender, users will no longer lose an important one-to-one conversation amongst low-content Event messages, broadcasted Page updates, and other noise. When a user visits their main Messages folder, they’ll only see active conversations with the people they choose. By making it so easy to continue the conversation, Messages will keep us in direct contact as effectively as the news feed keeps us in indirect contact.


"

Disqus for ully's online marketing

Disqus for ully's online marketing