Sunday 23 June 2013

wordpress Function Reference/get categories and Function Reference/wp get recent posts

Description

Returns an array of category objects matching the query parameters.
Arguments are pretty much the same as wp_list_categoriesand can be passed as either array or in query syntax.

Usage

 <?php $categories get_categories$args ); ?> 

Default Usage

<?php $args = array(
 'type'                     => 'post',
 'child_of'                 => 0,
 'parent'                   => '',
 'orderby'                  => 'name',
 'order'                    => 'ASC',
 'hide_empty'               => 1,
 'hierarchical'             => 1,
 'exclude'                  => '',
 'include'                  => '',
 'number'                   => '',
 'taxonomy'                 => 'category',
 'pad_counts'               => false );?>

Parameters

type 
(string) Type of category to retrieve
  • post - default
  • link
Note: type=link has been deprecated from WordPress 3.0 onwards. Use taxonomy=link_category instead.
child_of 
(integer) Display all categories that are descendants (i.e. children & grandchildren) of the category identified by its ID. There is no default for this parameter. If the parameter is used, the hide_empty parameter is set to false.
parent 
(integer) Display only categories that are direct descendants (i.e. children only) of the category identified by its ID. This does NOT work like the 'child_of' parameter. There is no default for this parameter. [In 2.8.4]
orderby 
(string) Sort categories alphabetically or by unique category ID. The default is sort by Category ID. Valid values:
  • id
  • name - default
  • slug
  • count
  • term_group
order 
(string) Sort order for categories (either ascending or descending). The default is ascending. Valid values:
  • asc - default
  • desc
hide_empty 
(boolean) Toggles the display of categories with no posts. The default is 1 for true or you can add '0' for false (show empty categories). Valid values:
  • 1 - default
  • 0
hierarchical 
(boolean) When true, the results will include sub-categories that are empty, as long as those sub-categories have sub-categories that are not empty. The default is true. Valid values:
  • 1 (true) - default
  • 0 (false)
exclude 
(string) Excludes one or more categories from the list generated by wp_list_categories. This parameter takes a comma-separated list of categories by unique ID, in ascending order. See the example.
include 
(string) Only include certain categories in the list generated by wp_list_categories. This parameter takes a comma-separated list of categories by unique ID, in ascending order. See the example.
  • list - default.
  • none
number 
(string) The number of categories to return
taxonomy 
(string or array) Taxonomy to return. This parameter added at Version 3.0 Valid values:
  • category - default
  • taxonomy - or any registered taxonomy
pad_counts 
(boolean) Calculates link or post counts by including items from child categories. Valid values:
  • 1 (true)
  • 0 (false) - default

Return values

(array) 
Returns an array of category objects matching the query parameters.
The complete content of $category is:
$category->term_id
$category->name
$category->slug
$category->term_group
$category->term_taxonomy_id
$category->taxonomy
$category->description
$category->parent
$category->count
$category->cat_ID
$category->category_count
$category->category_description
$category->cat_name
$category->category_nicename
$category->category_parent

Examples

Dropdown Box as used in Parent category at post category page

This is the code used in the build in category page. Code from 3.0.1
wp_dropdown_categories(array('hide_empty' => 0, 'name' => 'category_parent', 'orderby' => 'name', 'selected' => $category->parent, 'hierarchical' => true, 'show_option_none' => __('None')));
This slightly altered code will grab all categories and display them with indent for a new level (child category). The select box will have a name= and id= called 'select_name'. This select will not display a default "none" as the original code was used to attach a category as a child to another category (or none).
wp_dropdown_categories(array('hide_empty' => 0, 'name' => 'select_name', 'hierarchical' => true));

Dropdown Box

Here's how to create a dropdown box of the subcategories of, say, a category that archives information on past events. This mirrors the example of the dropdown example of wp_get_archives which shows how to create a dropdown box for monthly archives.
Suppose the category whose subcategories you want to show is category 10, and that its category "nicename" is "archives".
<select name="event-dropdown" onchange='document.location.href=this.options[this.selectedIndex].value;'> 
 <option value=""><?php echo esc_attr(__('Select Event')); ?></option> 
 <?php 
  $categories=  get_categories('child_of=10'); 
  foreach ($categories as $category) {
   $option = '<option value="/category/archives/'.$category->category_nicename.'">';
 $option .= $category->cat_name;
 $option .= ' ('.$category->category_count.')';
 $option .= '</option>';
 echo $option;
  }
 ?>
</select>

List Categories and Descriptions

This example will list in alphabetic order, all categories presented as links to the corresponding category archive. Each category descripition is listed after the category link.
<?php
$args=array(
  'orderby' => 'name',
  'order' => 'ASC'
  );
$categories=get_categories($args);
  foreach($categories as $category) { 
    echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
    echo '<p> Description:'. $category->description . '</p>';
    echo '<p> Post Count: '. $category->count . '</p>';  } 
?>

Get only top level categories

To get the top level categories only, set parent value to zero. This example gets link and name of top level categories.

<?php
$args = array(
  'orderby' => 'name',
  'parent' => 0
  );
$categories = get_categories( $args );
foreach ( $categories as $category ) {
 echo '<a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a><br/>';
}
?>

wordpress post code Template Tags/get posts Function Reference/get the ID

The most appropriate use for get_posts is to create an array of posts based on a set of parameters. It retrieves a list of latest posts or posts matching this criteria.get_posts can also be used to create Multiple Loops, though a more direct reference to WP_Query using new WP_Query is preferred in this case.
The parameters of get_posts are similar to those of get_pages but is implemented quite differently, and should be used in appropriate scenarios. get_posts usesWP_Query, whereas get_pages queries the database more directly. Each have parameters that reflect this difference in implementation.
query_posts also uses WP_Query, but is not recommended because it directly alters the main loop by changing the variables of the global variable $wp_query.get_posts, on the other hand, simply references a new WP_Query object, and therefore does not affect or alter the main loop.
If you would like to alter the main query before it is executed, you can hook into it using pre_get_posts. If you would just like to call an array of posts based on a small and simple set of parameters within a page, then get_posts is your best option.

Usage

 <?php $posts_array get_posts$args ); ?> 

Default Usage

<?php $args = array(
 'posts_per_page'  => 5,
 'offset'          => 0,
 'category'        => '',
 'orderby'         => 'post_date',
 'order'           => 'DESC',
 'include'         => '',
 'exclude'         => '',
 'meta_key'        => '',
 'meta_value'      => '',
 'post_type'       => 'post',
 'post_mime_type'  => '',
 'post_parent'     => '',
 'post_status'     => 'publish',
 'suppress_filters' => true ); ?>
Note: 'numberposts' and 'posts_per_page' can be used interchangeably.

Parameters

For full parameters list see WP_Query
See also get_pages() for example parameter usage.
get_posts() makes use of the WP_Query class to fetch posts. See the parameters section of the WP_Query documentation for a list of parameters that this function accepts.
Note: get_posts uses 'suppress_filters' => true as default, while query_posts() applies filters by default, this can be confusing when using query-modifying plugins, like WPML. Also note that even if 'suppress_filters' is true, any filters attached to pre_get_posts are still applied—only filters attached on 'posts_*' or 'comment_feed_*' are suppressed.
Note: The category parameter needs to be the ID of the category, and not the category name.
Note: The category parameter can be a comma separated list of categories, as the get_posts() function passes the 'category' parameter directly into WP_Query as 'cat'.
$post_mime_type
(string|array) (Optional) List of mime types or comma separated string of mime types.
Default: None

Return Value

(array) 
List of post objects. See get_post() return values.
Unlike get_pages()get_posts() will return private pages in the appropriate context (i.e., for an administrator). (See: Andreas Kirsch, WordPress Hacking II, January 24, 2009-- accessed 2012-11-09.)

Examples

Posts list with offset

If you have your blog configured to show just one post on the front page, but also want to list links to the previous five posts in category ID 1, you can use this:
<ul>
<?php

global $post;

$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );

$myposts = get_posts( $args );

foreach( $myposts as $post ) : setup_postdata($post); ?>
 <li>
          <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
<?php endforeach; ?>

</ul>
Note: With use of the offset, the above query should be used only on a category that has more than one post in it, otherwise there'll be no output.

Reset after Postlists with offset

If you need after the loop, the post you had before joining the foreach, you can use this:
<ul>
<?php
global $post;
$tmp_post = $post;
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
 <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
</ul>

Access all post data

Some post-related data is not available to get_posts by default, such as post content through the_content(), or the numeric ID. This is resolved by calling an internal function setup_postdata(), with the $post array as its argument:
<?php
$args = array( 'posts_per_page' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>
 <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
 <?php the_content(); ?>
<?php endforeach; ?>
To access a post's ID or content without calling setup_postdata(), or in fact any post-specific data (data retained in the posts table), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. To display or print this data on your page use the PHP echo command, like so:
<?php echo $post->ID; ?>

Latest posts ordered by title

To show the last ten posts sorted alphabetically in ascending order, the following will display their post date, title and excerpt:
<?php
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ($postslist as $post) :  setup_postdata($post); ?> 
 <div>
  <?php the_date(); ?>
  <br />
  <?php the_title(); ?>   
  <?php the_excerpt(); ?>
 </div>
<?php endforeach; ?>

Random posts

Display a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:
<ul>
<?php
$args = array( 'posts_per_page' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
 <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

Show all attachments

Do this outside any Loops in your template.
<?php
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => null ); 
$attachments = get_posts( $args );
if ($attachments) {
 foreach ( $attachments as $post ) {
  setup_postdata($post);
  the_title();
  the_attachment_link($post->ID, false);
  the_excerpt();
 }
}
?>

Show attachments for the current post

Do this inside The Loop (where $post->ID is available).
<?php
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); 
$attachments = get_posts($args);
if ($attachments) {
 foreach ( $attachments as $attachment ) {
  echo apply_filters( 'the_title' , $attachment->post_title );
  the_attachment_link( $attachment->ID , false );
 }
}
?>

Get a post by its slug

Allows you to get a post ID by post slug. The caller_get_posts argument excludes sticky posts from this custom query.
<?php
$the_slug = 'my_slug';
$args=array(
  'name' => $the_slug,
  'post_type' => 'post',
  'post_status' => 'publish',
  'posts_per_page' => 1
);
$my_posts = get_posts($args);
if( $my_posts ) {
echo 'ID on the first post found '.$my_posts[0]->ID;
}
?>

Taxonomy Parameters

Show posts associated with certain taxonomy. If specifying a taxonomy registered to a custom post type then instead of using 'category' you would use '{custom_taxonomy_name}'. For instance, if you had a custom taxonomy called "genre" and wanted to only show posts from the "jazz" genre you would use the below code.
<?php
$args = array(
   'posts_per_page' => 8,
   'orderby' => 'rand',
   'post_type' => 'albums',
   'genre' => 'jazz',
   'post_status' => 'publish'
);
$show_albums = get_posts ( $args );
?>
Following example displays posts tagged with 'jazz', under 'genre' custom taxonomy, using 'tax_query':
$args = array(
 'tax_query' => array(
  array(
   'taxonomy' => 'genre',
   'field' => 'slug',
   'terms' => 'jazz'
  )
 )
);
$postslist = get_posts( $args );
Refer to the taxonomy parameters section of the WP_Query documentation for more examples.

Custom Field Parameters

Show posts associated with a certain custom field. Following example displays posts from the 'product' post type that have meta key 'featured' with value 'yes', using 'meta_query':

$args = array(
 'post_type' => 'product',
 'meta_query' => array(
  array(
   'key' => 'featured',
   'value' => 'yes',
  )
 )
 );
$postslist = get_posts( $args );

Convert an HTML Template to a WordPress Theme: How-

Though WordPress has a huge number of themes available, I often get clients asking me if it is possible to take a standard HTML / CSS template and transform it into a WordPress theme.The answer is yes, and to do the basic conversion, it is affordable and fast.The way I convert a template to a WordPress theme involves a few easy steps. In this post, I’ll explain how to get a simple conversion underway.
Step 1: Prepare
At this point, you should have an HTML file, a CSS file, and a directory of images for your template. Make any design changes now, because later you will need to edit more than one .html and one .css file. Where the main content of your page is, make sure there is only one ‘content block.’ You won’t need any others, as WordPress loops through this section to populate your page with posts.Once you have your design finalized, you are ready to cut that html file up into the component parts of your new WordPress theme.
Step 2: Slice ‘n’ Dice
Create a new directory for your theme. It is in this directory that you will place the PHP files, with content supplied by your converted template. Go through your HTML file, and mark each section in the file. The sections you are looking for are:
  • Header
  • Sidebar
  • Footer
  • Main Content (where your posts will go)
Mark the header, sidebar and footer sections with something like
1
<!-- HEADER STARTS/ENDS HERE -->
, and where your main content is, use
1
<!-- WP LOOP STARTS/ENDS -->
for the beginning and end of each section.Now create files called header.php, sidebar.php, and footer.php. Cut the code between the
1
<!-- -->
tags and paste it into the relevant files.Finally, take all the remaining code, and paste it into index.php. Replace the
1
<!-- SECTION STARTS HERE -->
tags for each section with the relevant php code:
1
<?php get_header();?>
or
1
<?php get_sidebar();?>
or
1
<?php get_footer();?>
Finally, copy your CSS file (rename it to style.css if necessary) and your image folder into your theme directory.
Step 3: Add a Dash of WordPress Code
Add the following to your header.php file:
1
2
3
<meta http-equiv="Content-Type"content="<?php bloginfo('html_type'); ?>;charset=<?php bloginfo('charset'); ?>" />
<title><?php bloginfo('name'); ?><?php wp_title(''); ?> </title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>"type="text/css" media="screen" />
You can find code to add to your sidebar and footer in the WordPress Codex.Lastly you need to add the WordPress Loop, the code which will generate all of your small business’ or personal blog content.Add the following above your
1
<!-- WP LOOP STARTS -->
comment in index.php:
1
<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
Where the article title would be (usually inside h1 or h2 tags) you should add this code to get the page or post title:
1
<a title="Click to read: "<?php strip_tags(the_title()); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
And the following code should replace your sample article:
1
<?php the_content("Read more..."); ?>
Add all the following above your comment:
1
<?php endwhile; ?>
Navigation between articles can be added:
1
2
3
4
5
6
7
8
9
<!-- Article Navigation -->
<div class="navigation">
    <div class="alignleft">
        <?php posts_nav_link('','','« Previous Entries') ?>
    </div>
    <div class="alignright">
        <?php posts_nav_link('','Next Entries »','') ?>
    </div>
</div>
You can then add this code for anybody who has an outdated link to a post or page:
1
2
3
4
<?php else : ?>
    <h1>Error: Not Found</h1>
    <p>The page you were looking for is not here.</p>
<?php endif; ?>
Step 4: Install
Once this is done, save the page as index.php, single.php, and page.php. You can customize each of these to have different display elements for the main page (index.php), single post pages (single.php), and pages (page.php).There are many more ways you can customize your theme, by adding additional WordPress features (see the WordPress Codex for examples), but for now, either zip all your files and upload your theme with the Theme Installer, or copy your theme folder to your wp-content/themes/ folder in your installation of WordPress.
Step 5: Final Tweaks and Maintenance
Once the theme is copied or installed, CHMOD all files to allow you to edit them within the WordPress theme editor (Appearance -> Editor), and continue editing and tweaking until you are happy with your new theme.

Word press

What is a "blog"?

"Blog" is an abbreviated version of "weblog," which is a term used to describe web sites that maintain an ongoing chronicle of information. A blog features diary-type commentary and links to articles on other Web sites, usually presented as a list of entries in reverse chronological order. Blogs range from the personal to the political, and can focus on one narrow subject or a whole range of subjects.
Many blogs focus on a particular topic, such as web design, home staging, sports, or mobile technology. Some are more eclectic, presenting links to all types of other sites. And others are more like personal journals, presenting the author's daily life and thoughts.
Generally speaking (although there are exceptions), blogs tend to have a few things in common:
diagram
  • A main content area with articles listed chronologically, newest on top. Often, the articles are organized into categories.
  • An archive of older articles.
  • A way for people to leave comments about the articles.
  • A list of links to other related sites, sometimes called a "blogroll".
  • One or more "feeds" like RSS, Atom or RDF files.
Some blogs may have additional features beyond these. Watch this short video for a simple explanation for what a blog is.

The Blog Content

Content is the raison d'être for any web site. Retail sites feature a catalog of products. University sites contain information about their campuses, curriculum, and faculty. News sites show the latest news stories. For a personal blog, you might have a bunch of observations, or reviews. Without some sort of updated content, there is little reason to visit a web site more than once.
On a blog, the content consists of articles (also sometimes called "posts" or "entries") that the author(s) writes. Yes, some blogs have multiple authors, each writing his/her own articles. Typically, blog authors compose their articles in a web-based interface, built into the blogging system itself. Some blogging systems also support the ability to use stand-alone "weblog client" software, which allows authors to write articles offline and upload them at a later time.

Comments

Want an interactive website? Wouldn't it be nice if the readers of a website could leave comments, tips or impressions about the site or a specific article? With blogs, they can! Posting comments is one of the most exciting features of blogs.
Most blogs have a method to allow visitors to leave comments. There are also nifty ways for authors of other blogs to leave comments without even visiting the blog! Called "pingbacks" or "trackbacks", they can inform other bloggers whenever they cite an article from another site in their own articles. All this ensures that online conversations can be maintained painlessly among various site users and websites.

The Difference Between a Blog and CMS?

Software that provides a method of managing your website is commonly called a CMS or "Content Management System". Many blogging software programs are considered a specific type of CMS. They provide the features required to create and maintain a blog, and can make publishing on the internet as simple as writing an article, giving it a title, and organizing it under (one or more) categories. While some CMS programs offer vast and sophisticated features, a basic blogging tool provides an interface where you can work in an easy and, to some degree, intuitive manner while it handles the logistics involved in making your composition presentable and publicly available. In other words, you get to focus on what you want to write, and the blogging tool takes care of the rest of the site management.
WordPress is one such advanced blogging tool and it provides a rich set of features. Through its Administration Panels, you can set options for the behavior and presentation of your weblog. Via these Administration Panels, you can easily compose a blog post, push a button, and be published on the internet, instantly! WordPress goes to great pains to see that your blog posts look good, the text looks beautiful, and the html code it generates conforms to web standards.
If you're just starting out, read Getting Started with WordPress, which contains information on how to get WordPress set up quickly and effectively, as well as information on performing basic tasks within WordPress, like creating new posts or editing existing ones.

Things Bloggers Need to Know

In addition to understanding how your specific blogging software works, such as WordPress, there are some terms and concepts you need to know.

Archives

A blog is also a good way to keep track of articles on a site. A lot of blogs feature an archive based on dates (like a monthly or yearly archive). The front page of a blog may feature a calendar of dates linked to daily archives. Archives can also be based on categories featuring all the articles related to a specific category.
It does not stop there; you can also archive your posts by author or alphabetically. The possibilities are endless. This ability to organize and present articles in a composed fashion is much of what makes blogging a popular personal publishing tool.

Feeds

A Feed is a function of special software that allows "Feedreaders" to access a site automatically looking for new content and then post updates about that new content to another site. This provides a way for users to keep up with the latest and hottest information posted on different blogging sites. Some Feeds include RSS (alternately defined as "Rich Site Summary" or "Really Simple Syndication"), Atom or RDF files. Dave Shea, author of the web design weblog Mezzoblue has written a comprehensive summary of feeds.

Blogrolls

blogroll is a list, sometimes categorized, of links to webpages the author of a blog finds worthwhile or interesting. The links in a blogroll are usually to other blogs with similar interests. The blogroll is often in a "sidebar" on the page or featured as a dedicated separate web page. WordPress has a built-in Link Manager so users do not have to depend on a third party for creating and managing their blogroll.

Syndication

A feed is a machine readable (usually XML) content publication that is updated regularly. Many weblogs publish a feed (usually RSS, but also possibly Atom and RDF and so on, as described above). There are tools out there that call themselves "feedreaders". What they do is they keep checking specified blogs to see if they have been updated, and when the blogs are updated, they display the new post, and a link to it, with an excerpt (or the whole contents) of the post. Each feed contains items that are published over time. When checking a feed, the feedreader is actually looking for new items. New items are automatically discovered and downloaded for you to read, so you don't have to visit all the blogs you are interested in. All you have to do with these feedreaders is to add the link to the RSS feed of all the blogs you are interested in. The feedreader will then inform you when any of the blogs have new posts in them. Most blogs have these "Syndication" feeds available for the readers to use.

Managing Comments


One of the most exciting features of blogging tools are the comments. This highly interactive feature allows users to comment upon article posts, link to your posts, and comment on and recommend them. These are known as trackbacks and pingbacks. We'll also discuss how to moderate and manage comments and how to deal with the annoying trend in "comment spam", when unwanted comments are posted to your blog.

.....................................................................................................................................................

Plugins

Plugins are tools to extend the functionality of WordPress. This article contains a list of plugins by category, and links to other plugin repositories. The core of WordPress is designed to be lean, to maximize flexibility and minimize code bloat. Plugins offer custom functions and features so that each user can tailor their site to their specific needs.
...................................................................................................................................................

Function Reference/get the ID

Contents

[hide]

Description

Retrieve the numeric ID of the current post. This tag must be within The Loop.

Usage

 <?php get_the_ID(); ?> 

Parameters

This tag has no parameters.

Returns

ID (int) 
The ID of the current post.

Examples

Store the ID

The ID can be stored as a variable using   <?php $postid get_the_ID(); ?> 

Post Anchor Identifier

get_the_ID() Can be used to provide a unique anchor in a script. For instance, a dynamically-generated drop down menu with actions for each post in an archive could have
<?php
$id = get_the_ID();
$dropdown = "<select name='dropdown-".$id."' >";
$dropdown .= "<option id='option1-". $id ."'>Option 1</option>";
$dropdown .= "</select>";
?>
This would allow us to use JavaScript to control the element as it has a unique ID, and when submitting it as a form through the POST or GET methods the dropdown box will be sent with a unique ID which allows the script to note which post it is working on. Alternatively a hidden variable could be sent which will allow the script to see which post the submission is referring to
<?php
echo '<input type="hidden" name="activepost" id="activepost" value="'.get_the_ID().'" />';
?>
If the ID is not called within PHP, then we can use the_ID rather than echo get_the_ID();

Change Log

Since: 2.1.0

Source File

get_the_ID() is located in wp-includes/post-template.php.

Related

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Convert HTML to WordPress

Create Your Own WordPress Theme from an HTML Template

WordPress has become the most widely used blogging platform in the world, estimated to be used on a quarter of a billion websites online today. WordPress works as a blog, but also as a straightforward content management system, ready to use with search-engine-friendly URLs and fully valid HTML and CSS.With so many sites using WordPress and only about 1,200 themes listed on WordPress.org, there are inevitably lots of sites looking exactly the same. You and your clients need to stand out, or end up being branded as “just another WordPress blog.”In this article, I’ll show you how to take an existing HTML and CSS site template and convert it into a theme for WordPress. Of course, WordPress theming is much too vast a topic to cover entirely in a single article, so I’ll provide you with some resources at the end to further your learning. It’s hoped, though, that this article will serve as a good introduction and give you a solid foundation to start learning aboutcreating your own WordPress themes.I’m assuming you already know HTML and CSS, and already have a site design that you want to adapt to WordPress. Being familiar with PHP is unnecessary, as I’ll be explaining every function you need as we use it.

WordPress Theme Basics

WordPress themes live in a folder inside the /wp-content/themes/ directory in your WordPress installation. Each theme’s folder includes a few essential components:
  • A main CSS file. This is just a regular CSS file, except for a few extra details at the top, which I’ll be explaining shortly. You can, of course, have more CSS files if you need to (a print style sheet, for example).
  • index.php, the main index file that WordPress loads when you’re using the theme.
The contents of the index.php page can also be split up into several other files, which would then be included in index.php. Normally, these are:
  • header.php: contains the first part of the template, usually starting from the doctype and extending to just after the page’s header (including the site and page title, and navigation elements).
  • sidebar.php: similar to the header.php file, it includes elements that appear in the sidebar. You can enable this to work with widgets in WordPress, or, if you prefer, you can enter the content directly into the theme files.
  • footer.php: normally called last in the page, and usually placed from the end of the page content through to the bottom of the web page.
  • comments.php: defines the structure of the comments section for each post. If you leave this out of your theme, the comments.php file from the default theme will be used.
There can be other PHP files, but these are optional. You can add files that provide a specific layout for certain pages, such as category pages, single posts, or posts with a given tag. It’s also common to have templates for site errors like 404s.Once you have your HTML template that you’re ready to convert—whether you’ve written it from scratch, had it designed, or bought it from a template marketplace—you can convert it into a WordPress theme in very little time.

Starting Your Theme

Ideally, before you begin, you need an installation of WordPress up and running, which is available free fromWordPress.org. When you’re creating the theme, it’s easiest to work on the files locally or on a local VM, although you could also work on a web server over FTP.First, you need a folder for the theme. This needs to be created inside /wp-content/themes/ in your WordPress installation directory. It’s as simple as creating a new directory with a name related to your theme. Inside this, you’ll start off with your style sheet, which also includes some information about the theme that will be used in the administration panel later.Create a CSS file named style.css, and add the following at the top of the file:
..........................
/*Theme Name: [A unique theme name here]Theme URI: [The theme website]Description: [A description]Author: [Your name]Author URI: [Your website].[Any other comments].*/
..........................................................

index.php

Next up, it’s the index.php file. The easiestway to begin is by copying and pasting all of the content from the mainHTML file in your site template into this new file.We’ll start by replacing some of the hard-coded information in the file with dynamic content that will be generated on the fly by WordPress.WordPress has a built-in function called bloginfo for accessing all types of information about the installation and the theme. We’ll use this to fetch the style sheet URL and the location of the RSS feed. bloginfo is extremely simple to use:
<?php bloginfo('stylesheet_url'); ?>
In this example, I’ve included the style sheet URL; however, it works for a whole range of parameters including the charset, blog description, and template directory. For a full list, see the WordPressCodex.Looking at your template, you now want to replace the link element pointing to your style sheet with a line like this:
Example 1.  (excerpt)
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css"  />
Everything between <?php and?> will be replaced by the return value of the function, which in this case will be the URL pointing to your style sheet. This is perfect, because your website will now contain a line like:
<link rel="stylesheet" href="http://example/blog/wp-content/themes/style.css" type="text/css" />
important: Wax On, Wax Off
The key to building WordPress themes is to take the process we’ve just gone through and repeat it for every bit of content on your site: take your existing HTML and find the parts of it that should be included dynamically. Then find the WordPress function that will return the value you want and insert it, either between the HTML tags or inside an attribute, as we did for the style sheet URL.

Assets

Of course, your CSS file most likely references a number of images, so it’s necessary at this point to move those over to your theme directory. While there are no set rules for how you name image and other asset directories within a theme folder, it’s worth adding a new folder called assets here, which will include things like images and JavaScript files. If you prefer, you can have separateimages and js folders, but for the sake of this article, I’ll assume you’re sticking with a single assets folder. Move all your images to the new folder.You need to change any references to the old image locations that existed before the template was converted to a WordPress theme to the new locations. Find and replace works in virtually every text editor out there, and is the easiest way to achieve this. Look for references to the old path (for example,images/ up to just before the filename, including the trailing slash), and replace them with the following:
<?php bloginfo('template_directory') ?>/assets/
This will change all references to the path to the new folder your theme lives in. The assetsdirectory is where the images are now housed.If the location of the images relative to the CSS file have changed, a quick find and replace from the old folder name to the new one should make short work of this.Now, you should have a copy of your HTML, CSS, and images all set up and working in WordPress. To check, save it and try setting WordPress to use your theme, and see what happens. You should receive a duplicate of the original HTML template, only now it’s being generated by WordPress. There should be no WordPress content in there just yet, though.

The Header, the Footer, and the Sidebar

The next task will be to split the content into the header, footer, sidebar if you have one, and the rest of the page. Bearing in mind that the header, footer, and sidebar code remains unchanged on all pages (as a general rule), start by working from the top of the
index.php
until you reach the beginning of your sidebar or your main page content (depending on which one is first in the source), and select everything from the beginning to this point. This will usually include your page title, logo, and navigation menu.Cut and paste this into a new file, and save it in the same location as your
index.php
file with the name
header.php
. The filename is important, as WordPress will go looking for this file when you ask it to insert the header in your pages. Speaking of which, let’s tell WordPress to do this. In the place of the code you cut out of
index.php
, put the following line:
<?php get_header(); ?>
code tells WordPress to include the content from your
header.php
file at that location in the page.Next, we’ll do the same for the page’s footer: cut all the footer material from
index.php
and paste it into a new file called
footer.php
, replacing it with:
<?php get_footer(); ?>
Finally, do the same action with your sidebar, saving it as
sidebar.php
and replacing it with
<?php get_sidebar(); ?>
.It’s worth checking again to see that your page is still working at this point. We haven’t made any changes, just split it up into separate files, but it’s good to verify that everything is still working.

Template Tags

At this point, your site is just showing static HTML contained in your template, rather than fetching live data from WordPress. It’s time to change that.In WordPress, you use template tags to tell WordPress what content to fetch and insert into a page. There’s a definitive list of them on the WordPress Codex, but if you’ve been following this far, you’ve already met a few of them!
get_header
,
get_sidebar
,
get_footer
, and
bloginfo
are all template tags.These tags can be added to any PHP file within the theme, so a good place to start is at the top of your site, with the
header.php
file.Let’s start at the very beginning of the file. The
Doctype
can remain as is. The opening html tag can include a lang attribute, and WordPress provides this with the
language_attributes
template tag. So, we can replace the html tag with:
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>
This will generate an attribute along the lines of:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
If you’ve included any scripts, it’s worth moving them to the
assets
folder, and changing any references to them as you did for the images. If you used a global find/replace to modify the image paths, it’s possible that the script paths were modified as well, though you’ll still need to move the JavaScript files themselves.For blogs, it’s a good idea to include links to your RSS feed and pingback URL in your head, as these will be automatically recognized by many browsers. Both of these links can be added using the
bloginfo
by including these lines:
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" /><link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
With that done, you now need to include the
wp_head
tag. This tag will pull in any JavaScript files or style sheets required by the WordPress plugins you’re using. This is vital, as those plugins may fail to function as intended. All you needis the line:
<?php wp_head(); ?>
The final element in the HTML head is the page title. Most WordPress themes use some variation of the following:
<title><?php bloginfo('name'); ?> <?php wp_title('-'); ?></title>
This will include the name of the blog, which can be defined in the WordPress settings, followed by the page title. For example, if the page is a single article, it will show the article’s title. The
'-'
in brackets is the separator, which will be placed before the
wp_title
content if (and only if) there’s a title to display. This means that the title of my blog’s home page will be “My Blog,” whereas the title of an article on my blog will be “My Blog: Article Title.” WordPress is smart, and will only include the separator if it’s needed.Still in the
header.php
file, we’ll now move onto the body tag. This part will vary more depending on the structure of your template, but work through it andlook for any content that should be pulled in from WordPress. For example, if the website title appears in the code as
<h1>My Blog</h1>
, it should be replaced with
<h1><?php bloginfo('name'); ?></h1>
.The template tags you’re most likely to need at this point are:
  • get_option('home');
    : the URL of the blog’s home page
  • bloginfo('rss2_url');
    : the URL of the blog’s RSS feed
  • bloginfo('description');
    : the description of the blog, as defined in the WordPress settings
As with the other template tags we’ve seen, these need to be put inside
<?php ?>
tags; they can sit anywhere inside the PHP file, even inside your HTML tags.Moving your site’s navigation into WordPress can be a bit trickier. There are template tags that can provide you with lists of categories or lists of pages, which you can then use to create parts of your navigation. The template tags are
<?php wp_list_categories(); ?>
and
<?php wp_list_pages(); ?>
, and will provide you with lists of hyperlinks that you can style as you would a static navigation list. However, sometimes you need your pages to appear in a specific order, or you need to exclude certain pages. Much of this is possible by passing certain parameters to
wp_list_pages
. To learn more about how to manipulate this tag, read up about it on the Codex.Moving on, if you’ve included a sidebar you’ll want to include some other elements, like links to categories and pages, or a tag cloud. Even if your layout has no sidebar, there may be other areas of the theme where it would be sensible to add these tags.

Widgets

If you plan on releasing your theme to the wider community, it’s important that you widgetize the sidebar. Widgets are chunks of content that can be added to predefined areas in a theme via the WordPress administration panel. For example, you could have a widget area at the top of your sidebar, where the blog owner could easily add a list of pages or an arbitrary block of HTML. Widgets are beyond the scope of this tutorial, but you can read more about them on the WordPress Codex.Other tags you may like to add to your sidebar include (again wrapped in
<?php ?>
tags):
  • wp_list_authors();
    : lists all the blog’s authors as li elements. If they have authored posts, their name will be a link to a page showing all their posts.
  • wp_list_bookmarks();
    : outputs the links that have been added in the Links section of the administration panel, and is also wrapped in li tags.
  • wp_tag_cloud();
    : displays a cloud of all the tags that have been added to your posts.
Your footer section should be easy to handle now that you have a feel for template tags. If you need to output content we haven’t covered here, be sure to look for an appropriate template tag in the Codex. Remember to close any tags that are open in your
header.php
file, such as body or any wrapper divs.As you’ve worked through this, you probably tried viewing the page at various points to test it. Whether or not that’s the case, when you view the page now, it should include all the content being pulled from WordPress, except the main body of the page.

The Main Blog Content

Now that we’ve defined the content for the header, footer, and sidebar, it’s time to turn to our page’s core content. We’ll now go back to our
index.php
file and implement the WordPress Loop. The Loop is the mechanism WordPress uses to cycle through the posts that are to be displayed on a given page, and output the content for each of them.It begins like this:
<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
These two lines check to see if any posts have been provided. Depending on which page you’re viewing, different posts will be available. For example, on the main blog page, a certain number of the most recent posts will be shown. If you’re viewing a specific post, then only that post will be provided to the Loop. For category, tag, or author pages all posts belonging to that tag, category, or author will be shown.With those two lines in place, we’re now inside the loop. We now need to instruct WordPress to execute a few lines of code individually for each post in the set. For example:
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2><small><?php the_time('F jS, Y') ?> by <?php the_author() ?> </small>
This example section begins with an h2 tag containing the post title, which is linked to that post’s page. Beneath this, the post time and author are listed, wrapped in the small tags. There are a number of new template tags here, and many others you can use to customize your template to display the HTML you want for each. Here are some of the more common ones:
  • the_permalink()
    : the URL of the permanent hyperlink to the post.
  • the_title()
    : the post’s title.
  • the_time('F jS, Y')
    : displays the post’s date in “January 1st, 2010” format. To format the date differently, replace
    'F jS, Y'
    with another PHP date format string.
  • the_author()
    : displays the name of and links to the archive for the user who wrote the post.
  • the_content()
    : inserts the post content. There’s no need to place this inside
    <p></p>
    tags, as this will be done automatically.
  • the_category()
    : displays the name of and links to the archive of the post’s category.
The easiest way to make your post display match your existing template is to cut and paste your template’s sample content code inside the WordPress loop. Then insert the appropriate template tag into each part of the post’s HTML. Once you’ve included everything you want, it’s time to end the loop with
<?php endwhile; ?>
. This runs once all the posts have been processed. Ideally, it should be followed by some navigation controls:
<div class="navigation">  <div class="alignleft"><?php previous_posts_link('&laquo; Previous Entries') ?></div>  <div class="alignright"><?php next_posts_link('Next Entries &raquo;') ?></div></div>
Each page displays a certain number of posts, as defined in the WordPress settings. These controls will allow your visitors to navigate back to older posts with Next and Previous links. The parameter passed to
previous_posts_link
and
next_posts_link
(the string in parentheses) the text to be used for the link.At this point, note that the
while
structure has been closed, but the
if(have_posts())
is still open. I need to elaborate on this a little. It’s possible that a page will have no posts to display (for example, your home page before you’ve added any posts, or an archive page for a month in which no posts were published.) In those cases,
if(have_posts())
will evaluate to
false
, so none of the template code you’ve just written will be run.For those cases, you’ll want to provide some fallback content. So,we first need to define the
else
condition, and thenclose the
if
statement with PHP’s
endif
keyword:
<?php else: ?><p>Sorry, there are no posts to display.</p><?php endif; ?>
For this example, we’ve simply added a paragraph telling the that there were no posts found for the page. You could also add a box or links to other parts of your site, to help visitors find their back to the content they’re looking for.

Other Pages

In our simple example,
index.php
is being as the template for every page on the site. But if you want to modify aspect of the template only on a specific page (or group of WordPress lets you do that easily. All you need to do is
index.php
with more specific template files. example, you can create a
single.php
file, and template will be used for single post pages instead of
index.php
file. Similarly, there
category.php
(for category
search.php
(for search results),
home.php
(for the home page), and a number of othertemplate files you can create to customize each separate area of yoursite.
...........................................................................

Featured post

Life Infotech now a leading brand in the field of technology training

  Life Infotech now a leading brand in the field of technology training & its invites students around the nation to be a part of the Tra...