Showing posts with label Plugin. Show all posts
Showing posts with label Plugin. Show all posts

Saturday, March 16, 2013

Create Wordpress plugin from scratch

This tutorial will explain how to create Wordpress widget from scratch. You will also learn how to implement configuration page for your widget.

Getting started

You should already have Wordpress installed, either on your local machine or on a testing server. For this tutorial we will use the Wordpress version 2.7. You should also have a theme that support widgets. You could use the default one or make a wordpress theme from scratch and widgetize it.

Widget name

The first task in creating a Wordpress widget is to think about what the widget will do, and make a (hopefully unique) name for your widget. Check out Plugins and the other repositories it refers to, to verify that your name is unique; you might also do a Google search on your proposed name. The name can be multiple words.

Widget files

We will start by creating a folder widget-name in our wp-content/plugins/ directory, where Wordpress stores all it's plugins. It's a good idea to always create a folder for your plugin, even if it consists only of 1 file, so you could add more files later. The next step is to create our main widget file widget-name.php. To make Wordpress recognize it as a plugin we should add a specific header to it, that describes our widget.

Widget header

<?php
/*
Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the Plugin.
Version: The Plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
*/
?>
Our widget should appear in Wordpress administration area in inactive plugin list. Information about your widget will be extracted from the header of a main widget file. To continue developing our widget we must activate our plugin by clicking Activate to the right of the plugin entry. Activate plugin

Creating widget structure

There are different ways to create a Wordpress widget. I prefer creating it as a static class, but the downside of this method it that our widget will support php5 only, anyway I believe, that support for php4 can already be dropped. So let's create our main class, that will contain all widget methods.
error_reporting(E_ALL);
add_action("widgets_init", array('Widget_name', 'register'));
class Widget_name {
  function control(){
    echo 'I am a control panel';
  }
  function widget($args){
    echo $args['before_widget'];
    echo $args['before_title'] . 'Your widget title' . $args['after_title'];
    echo 'I am your widget';
    echo $args['after_widget'];
  }
  function register(){
    register_sidebar_widget('Widget name', array('Widget_name', 'widget'));
    register_widget_control('Widget name', array('Widget_name', 'control'));
  }
}
Our plugin should not throw any level errors (even notices), so we should turn error reporting on while we are developing. We will remove this line when the widget will be finished. The add_action function hooks our register method to an widgets_init event. You can read about it in Wordpress codex. It takes the action hook name as its first parameter and the callback function as a second parameter. You should definitely read about callbacks in php manual. To make widget appear in widgets menu in Wordpress we must register them first, we do that with our register method which creates a widget itself and a control panel for it. The before_widget, after_widget, before_title and after_title in widget method are required for compatibility with various themes. Activate widget Navigate to widgets page in administration area and activate it. To do that press add button next to your widget. It should appear at current widgets column, you can press edit button next to it too see the control panel. Don't forget to press save changes button! The text from your widget method should appear in your blog sidebar. Your widget in sidebar

Saving Widget Data to the Database

Most WordPress Widgets will need to get some input from the site owner or blog users and save it between sessions, for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are two basic methods for saving Widget data in the database.

WordPress Options

This method is appropriate for storing relatively small amounts of relatively static, named pieces of data - the type of data you'd expect the site owner to enter when first setting up the Widget, and rarely change thereafter. Option values can be strings, arrays, or PHP objects (they will be "serialized", or converted to a string, before storage, and unserialized when retrieved). Option names are strings, and they must be unique, so that they do not conflict with either WordPress or other Plugins. Here are function you will need to modify options.
add_option($name, $value);
update_option($name, $new_value);
delete_option($name);

Create a custom database table

This method is appropriate for data associated with individual posts, pages, attachments, or comments -- the type of data that will grow as time goes on, and that doesn't have individual names. See Creating Tables with Plugins for information on how to do this.

Plugin Installation

If you need to install default data for your widget it is best to use activation hook. It takes 2 parameters. First one is a path to the main plugin file inside the wp-content/plugins directory. And the second one is the function to be run when the plugin is activated. Any of PHP's callback pseudo-types will work. We will add activate method that will install default data for our widget.
error_reporting(E_ALL);
add_action("widgets_init", array('Widget_name', 'register'));
register_activation_hook( __FILE__, array('Widget_name', 'activate'));
register_deactivation_hook( __FILE__, array('Widget_name', 'deactivate'));
class Widget_name {
  function activate(){
    $data = array( 'option1' => 'Default value' ,'option2' => 55);
    if ( ! get_option('widget_name')){
      add_option('widget_name' , $data);
    } else {
      update_option('widget_name' , $data);
    }
  }
  function deactivate(){
    delete_option('widget_name');
  }
  function control(){
    echo 'I am a control panel';
  }
  function widget($args){
    echo $args['before_widget'];
    echo $args['before_title'] . 'Your widget title' . $args['after_title'];
    echo 'I am your widget';
    echo $args['after_widget'];
  }
  function register(){
    register_sidebar_widget('Widget name', array('Widget_name', 'widget'));
    register_widget_control('Widget name', array('Widget_name', 'control'));
  }
}

Creating widget control panel

We should use our control method for displaying and updating form with widget options. Here is a basic template for it.
function control(){
  $data = get_option('widget_name');
  ?>
  <p><label>Option 1<input name="widget_name_option1"
type="text" value="<?php echo $data['option1']; ?>" /></label></p>
  <p><label>Option 2<input name="widget_name_option2"
type="text" value="<?php echo $data['option2']; ?>" /></label></p>
  <?php
   if (isset($_POST['widget_name_option1'])){
    $data['option1'] = attribute_escape($_POST['widget_name_option1']);
    $data['option2'] = attribute_escape($_POST['widget_name_option2']);
    update_option('widget_name', $data);
  }
}
You should be able to access it on the widgets page. Widget options

Conclusion

I hope this tutorial gave you all the information you need to build your first Wordpress widget. If you have something to add or found an error, please feel free to post a comment below. And I want to add that Wordpress codex is a great source of information. 

Sunday, March 10, 2013

WordPress Plugins & The Security Risk

WordPress a common and famous platform for blogging and wordpress plugins are very common and make the life of blogger easy

because a plug in can perform the work fast and accurately and it does not require so much technical knowledge and skills.

WordPress plugins are available for different purposes like to tweak your blog , for SEO purpose, social sharing purpose

and for security purpose. There are so many plugins are available to provide the security of wordpress blog and they

usually called the plugins to secure a wordpress but these plugins itself has several vulnerabilities and these plugins

also plays an important role to compromise a wordpress blog.



The point is very simple that the plugins may be very dangerous for the security of wordpress blog, so what are the

security risks? And how an attacker can take the advantages of insecure wordpress plugins ?



The biggest example is timthumb vulnerability, timthumb is a script and a plugin used for crop the images but meanwhile

timthumb can be used to hack into a website, there are so many other techniques that an attacker may use to hack into a

wordpress blog, for example a malicious person has created a plugins that contain the code of the malwares and can easily

hijack the session of the visitors, now the attacker might use some social engineering and the promotion techniques to

promote the plugins and suppose that the thousands innocent bloggers has installed the plugins on their blog it means that

their visitors can be redirect to the malicious website and can be the victim of the iFrame injection security attack.



The other point of consideration:



    Whenever you install a plugin, the extra php code will insert into the core wordpress files.
    Extra plugins are the burden on the administration and it consume space.
    Old plugin may cause the compatibility problem with your current (latest) wordpress software, so the plugin will break

and disclose the sensitive information of the server.
    Third party plugins may use some data from the third party website, let suppose the other website has been compromised

and the worm spread itself then your website will be the next victim.



Although the importance of automatic scanners and plugins exist but manual review and manual security checklist has its own

importance and we should not neglect it, beside automatic scanning do review the security of your wordpress blog by

manually and do not forget to review of the source code of plugins.



The main tips to remain secure from the plugins risk is to active on the plugins community, learn about the latest changes,

update the plugin whenever available.

Friday, March 8, 2013

How to Increase Page views and decrease rebound Rate in WordPress



When beginning out, most bloggers accept as true that it is super hard to get persons to your blog. while most professional bloggers believe that getting persons to your blog is the easy part. Getting the users to stay on your location is harder. Most users come to your site and end up departing without even going to the second sheet. When a client leaves without even going to the second page, it rises your bounce rate. It furthermore decreases your page views per visit. On a bigger image, it declines your publicity revenue. In this item, we will share with you tips and tricks that will help you boost page views and decrease bounce rate in WordPress.

 Before we start
permits cover some basics considering terminology and expertise. Bounce rate comprises the percentage of tourists who go in your site and “bounce” (leave the location) rather than continue examining other sheets within the identical location. sheet view is a demand to load a single sheet on an internet location. We use Google Analytics to track our data. You are greeting to use another analytics service, or you can simply establish Google analytics in your WordPress site.

Now that we have taken care of the rudimentary terminology, you are likely marvelling why the heck do these figures matter?

If you are running a site that is mainly monetized by banner publicity, then the number of page views issue. If you are endeavoring to build a loyal assembly, then the number of rebound rate affairs. Also the smaller your rebound rate, the better ads eCPM (cost per thousand) or CPC (cost per bang) you will get. When the identical client views the next sheet, your publicity provider most expected has a better publicity to assist them therefore giving you a higher eCPM or CPC.

We have consulted with a allotment of clients helping them increase their page views and decrease bounce rates. We have furthermore finished a allotment of experiments on our own sites like List25. So all the procedures that we will share are the ones that we have utilized in the past and understand that they work.

Interlink Your Posts
Anytime that you can interlink your other mails inside the post content, you are going to glimpse an increase in page views. In WordPress 3.1, interlinking got even simpler because you can simply seek for the mail you desire to link while supplementing links. Interlinking techniques work large when you have a location with a lot of items. If you are just beginning out, then you will be a bit restricted. So how do you proceed back and interlink older items when you have something new? You can manually do it, but it will take some time. There are plugins that permits you mechanically link keywords in WordPress (Although that item is displaying you how we did this for affiliate links, you can use it for internal connecting purposes as well). Not only does interconnecting help you increase page views and reduce bounce rates, it also assists with SEO as well.

If you want to glimpse an example of interlinking, then just gaze at the paragraph overhead.

Show Related mails After the Post

One of the major causes why the user depart your blog after reading the post is because you are not displaying them what to do next. By showing the user with a register of “related posts” or “other popular posts”, you may get them to go on to visit another mail in your site. There are a lot of ways you can add related mails to your blog. You can use a plugin called YARPP that has its sophisticated algorithm that picks the associated mail. You can display associated mails by class or tags without using a plugin. You can furthermore display associated mails by displaying other mails by the same scribe.

Show Excerpts on Front / Archive sheets
Showing excerpts on front/archive sheets have two benefits. First, it decreases sheet burden time. Second, it helps boost the page views. You should nearly not ever display full posts on your front sheet or archive sheet. envisage having like 25 images in one mail, and then have 5 of those on one page. It would be a awful client know-how because of (slow load time and super long sheet) which would make the user leave your location. We have a tutorial on how to display mail excerpts in WordPress topics. Most good topic structures like Genesis, Thesis, Headway etc. currently have this option built-in.
Dividing up Long mails
Are you composing a super long mails? Well, you can split it into multiple pages utilizing the WordPress <!--nextpage--> tag in your mail. Simply add it while you desire, and your mail will divide into multiple sheets. You can see an demonstration of how we divide our mails into two pages or even into five sheets. You have to be very cautious when doing this because if you do not have a adequate allowance of content on each sheet, then the client might get pissed of. We have glimpsed a alallotmentment of large-scale title sites like Forbes, NY Times, partition road periodical and others utilize this technique.
Interactive Sidebar
Your sidebar can play a vital function in expanding page views and decreasing bounce rate. You can display your popular mails in the sidebar. You can even customize it to display well liked mails by week, month, all time. You can also display your most recent mails only on single mail pages. We have glimpsed sites that conceive made-to-order images to navigate to exact mails of theirs. You can integrate other parts of your location in your sidebar for example look at our WordPress Coupons part or the gallery part in the sidebar.
Boost Random Browsing
On List25 we conceived a feature called I’m Feeling inquisitive. When a client bangs on this button, they will be redirected to a random post in WordPress. We put the button in our header bar which was a very warm spot. After glimpsing good outcomes, we completed up putting it on WPBeginner as well and called it Explore.

How to conceive a photo Album in WordPress without a plugin

In the past, we have shown you how to add a gallery in WordPress with a light box effect. That item only wrappings the exterior of the WordPress functionality. Recently, we had a client that liked us to create a photo gallery coordinated by monthly albums. They wanted the user to be adept to bang on the album photo to glimpse all posts recorded in that month’s album. Each photo should have its own individual sheet with data about the person taking photos and their URL. commonly persons would resort to plugins like NextGen Gallery or another to accomplish certain thing like this. We liked to bypass using a third party plugin therefore we determined to use the core-functionality that WordPress boasts to create certain thing that works. In this item, we will show you how to create a monthly photo album gallery in WordPress without a plugin.

What we are trying to make:
Before we start, lets take a gaze at what the final conclusion is suppose to gaze like:
When the client bang on the Albums sheet, they will glimpse an archive in a grid brandish where each album begins out with it’s distinguishing cover and all the photos in it. The concept was to have one album per month. 

If the user bangs on the album’s cover photo, they will be taken to a sheet just for that album where you can give the client some backdrop information as well as records all the photographs in that album.

If the client bangs on the photo, then they will be taken to the single photo sheet where they will see the title of the photograph. Photographer’s title and their site’s URL.

How we are going to make it?
As you can see from the description above, all of the characteristics needed can be finished using the built-in WordPress functionality. We can heal each monthly album as a post, so each album can have its own lone page with some backdrop info etc. Each likeness will be treated as an addition (thus getting its own lone page). We will use the built-in featured thumbnails for album cover photograph. You can use the default posts, if the whole site’s reason is this photo album gallery, but if you have a blog as well, then this desires to be conceived in a custom post kind.

Let’s conceive a Photo Album Gallery

First thing you should do is conceive a site-specific plugin (or even a project-specific plugin).

If you are going to use made-to-order Post kinds for your task, then you should generate the ciphers and paste it in your site-specific plugin. You can furthermore watch our video on how to conceive Custom mail Types.

Next thing you need to do is list added image dimensions in WordPress for the grid display.
Example would be:

1
add_image_size( 'album-grid', 225, 150, true );

After the added likeness dimensions, let’s add some added fields to the newspapers uploader. This will permit you to add Photographer’s title and their URL when you upload each image. This is the cause why we wrote an item about it two days ago.

How to add additional areas to the WordPress newspapers Uploader
one time you have finished this, permits go ahead and add some albums (posts). Upload all images that you desire to attach to that album. Then attach a distinctive cover photo and set it as a boasted image. You can add the backdrop info in the content area of the mail.

Now that you have a couple of albums in the backend, permits put the cipher to brandish it.
Let’s say that your custom mail kind was called albums. So you will conceive a template file called archive-albums.php. Paste the header codes, the footer ciphers, sidebar and other conceive elements that you want. conceive a mail loop. interior that mail loop, we are going to brandish all additions from a mail except the thumbnail which will connection to the single likeness page. We will also add the boasted mail thumbnail (album cover photo) individually and connection that to the single mail page (album page).

We decided to style the grid images using the list element. The code looks like this:

<li class="album-grid"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('album-grid'); ?></a></li>
 
<?php if ( $post->post_type == 'albums' && $post->post_status == 'publish' ) {
               $attachments = get_posts( array(
                       'post_type' => 'attachment',
                       'posts_per_page' => -1,
                       'post_parent' => $post->ID,
                       'exclude'     => get_post_thumbnail_id()
               ) );
 
               if ( $attachments ) {
                       foreach ( $attachments as $attachment ) {
                               $class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
                               $title = wp_get_attachment_link( $attachment->ID, 'album-grid', true );
                               echo '<li class="' . $class . ' album-grid">' . $title . '</li>';
                       }
                       
               }
        }
?>


The main CSS style that you really have to worry about is the class .album-grid

.album-grid{width: 225px; height: 150px; float: left; list-style: none; list-style-type: none; margin: 0 18px 30px 0px;}

This would permit each likeness to be placed appropriately in the grid, and we will get the method how we desire it.

Next thing you need to do is conceive a single-attachment template. This will be the sheet where the user will be taken to, so they can view each individual likeness. They will glimpse the likeness name, photographer’s title and photographers URL here. You can follow our tutorial on How to Create a Custom Single additions Template in WordPress.

seem free to method the lone template although you like.
Now the only thing left in the register is to conceive an individual albums sheet. afresh presuming that your custom mail kind is called albums, you will need to conceive a single-albums.php file. Copy all the header, footer, sidebar, or any other design components that you want.

In the loop element fundamentally do the same thing that we did with the archive-albums template. Before you add the boasted likeness and the additions grid though, you need to add the album title and description. Which can be finished by easily adding the cipher like this?

<h1><?php the_title(); ?></h1>
<div class="entry-content"><?php the_content(); ?></div>
 
//Insert grid code below this line

Ta ad, we are done. We just created a monthly photo album gallery in WordPress without using any plugin. Let us know if you have any questions.

Create a Multi-Layout Portfolio with WordPress



WordPress, as a content management system, is frequently used for creating portfolio websites. With the progress of consumer interface design and functionalities, a new tendency has emerged: displaying portfolio substance in unrelated layouts. This tutorial particulars the method of creating a committed portfolio section in WordPress’ backend, and using jQuery and CSS3 to display the portfolio in a fashionable approach.

In this tutorial, we are going away to expansively use dominant facial appearance of WordPress, such as custom posts, custom taxonomies, and we’ll also inscribe a function to fetch our personal custom excerpts.

Step 1 - Installing WordPress and Initializing the Theme.

The initial step in building our portfolio website is to install WordPress. This is a easy task, and, even superior, the majority web hosts out there make available one click installers. However, if you are new to this, here is an awesome guide to facilitate you out with the installation.
Once the installation has fulfilled, we should after that create our custom theme which will show our portfolio. There are a variety of methods for creating custom themes. Several like better to create a new blank white template, even as others settle on to create child themes of the new TwentyTen template. For this lesson, we will make use of the Starker's theme, by Elliot Jay Stocks. It's a totally empty theme with no styling; it’s a immense base to create our theme on. Edit the styles.css file, and modify the theme name referenced at the top. To install the theme, merely paste the theme folder in the wp-content > themes folder. Once the theme is installed, you can make active it by obtainable to the themes page.

Step 2 - Planning the Layout

Our portfolio site will not hold much data. A basic portfolio site contains images of the projects, several tags to classify the projects, and a short explanation of each. The multi-layout theme will function in such a manner that the user can select stuck between a grid and list layout. Like numerous multi layout websites accessible, we are not going to fill a unusual page when the user clicks on the list view or the grid view. As an alternative, we’ll use AJAX to asynchronously load in the new observer. This is the essential design of how our portfolio site will emerge in grid mode:

On one occasion the user clicks on the list view manage, the entire layout will smoothly modify to a list view which will include the title of the project, the tags associated with it, and a short explanation.

Step 3 - Setting up the Backend

Intended for our portfolio, we require to register a custom post type, called “project.” We can modify every portion of a WordPress post. For example, we can modify the labels occupied, select various features for the post like to comments, thumbnails, excerpts, etc.
To execute a custom post, edit the functions.php file positioned within the theme folder. It holds a lot of predefined code, as the naked Starkers theme provides some functionalities of the evasion TwentyTen template. Don’t be scared or confused; you can add on the subsequent code either at the bottom or top of the functions.php file.
We fastener our custom function to the initialization (init) action in the subsequent technique:

This project_custom_init method will be used to register the custom post category in the WordPress database.


You can discover in recognize about the method engaged in registering a custom post variety here.
he register_post_type method requires a surname for the custom post, and a set of arguments, which define the individuality of the custom post. Firstly, we need to define the labels for the custom post. These labels will be used for the custom post in the WordPress admin.

On one occasion we’ve distinct the labels, we need to describe the set of influence for the custom post type. The labels array define earlier is going to be an argument as well. Formerly the arguments are defined, we register the custom post nature as “project”.


Create Custom Messages for the 'Project' Post

We can also optionally insert custom post for the custom post type. These post will be showed in the WordPress dashboard while we edit or update the custom post. We can do this by creating a strain for the post simplified messages in the following way:

Registering a Custom Taxonomy

We after that require significant a custom classification for the tags to be used with each of the portfolio items. You can learn more about the register classification manner here.


Go back to your WordPress dashboard, and open the media settings from the settings tag. Here, you comprise to set the evasion bulk for the portfolio image thumbnails. You’ll also observe in the sidebar that the “Project” custom post nature has been effectively registered, along with the custom classification, “tags.” We can inventory the default thumbnail size by means of the set_post_thumbnail method, but I’ll reveal another way to attain this. You can gain knowledge of more about how to place post thumbnail sizes programmatically here.


Create Demo Portfolio Items

Create several demo portfolio items by going away to projects and clicking on add new. We need a title for the project, the content, and a thumbnail. We can observe that a tag segment has also appeared and confirms that our custom classification was effectively registered. Add several tags for the portfolio stuff, as well.

Step 4 Coding and Styling The Template

Coding the static template

To craft the theme, we will first craft a static HTML/CSS3 pattern for the website. This separates the two errands of making the website look unswerving with the design, and enticing the content from the database. Coding the theme openly may be a bit puzzling for beginners occasionally – specially, if a lot of content is exist in the theme. Create three folders, named
“css”, “images” and “js,” respectively. The common formation for the main content locale will be like so:


Style the Template

Styling the template is needy on you. You can research with unlike colors and images to suit your desires. But for this template, we are arrival to create a dark grime theme and use some fun CSS3 to accomplish those slight hover effects and transparency. The slicing up of the design into metaphors is rather. As such, I won’t go over the minutiae here.
The following are the common styles for the project record. We will later do explicit styling for each grid layout manner and a list design mode depending on the current class of the folio list.


Also create note that we are not using the common opacity method of achieving transparency using CSS3. By means of the opacity method also affects the brood of the parent container on which the opacity is useful. As an alternative, we are using the RGBa method of adding up backdrop colors to the container, and using the alpha worth to control the transparency of the container.


You can learn more about the RGBa Property in this remarkable article.


This does not involve the transparency of the children fundamentals. We also need to create IE definite CSS code to sustain the alpha transparency.


In the HTML makeup, you will perceive that there is a class prearranged to the portfolio record.


Essentially, the “grid” class is used to show the list in a grid sight and the “list” class is used to show the list in a list view. In the grid mode, all the extra content is unseen from the user, and in the list manner, all the content is able to be seen to the user. We have two take apart sets of styling for each manner. The styles for the grid manner are as follows:

List manner styles are as follows. At any instant, only one of the grid or list styles is dynamic.


We after that will use jQuery UI to change the class of the folio record with deference to the layout button clicked by the user. We’re detecting the click occasion of the layout manage buttons, enticing the current class and the new class to be activated, and then using the add and remove class methods to modify the classes. We also have a set of parameters which identify the velocity of the events enchanting place.


Step 5 Integration with the WordPress Theme

Now that we have finished the static adaptation of the site, we can amalgamate it with the WordPress theme in a material of minutes. All we require to do is ring through the posts using a wp_query object with a query for the institution post type. Then, we lay the content in the respective position in the template.

Edit header.php

Initially, we need to change the header.php template, and embrace our custom JavaScript files. In this lesson, we’ll embrace jQuery using the Google’s CDN version. We will deregister the jQuery provided by WordPress, and register Google’s CDN version of jQuery. Paste the following snippet in your functions.php file.



Be in motion the css, js and images folders – that you shaped formerly for the motionless template – to the WordPress theme folder. Insert the jQuery UI custom file, and the major script file in the header. Make sure it is inserted below the wp_head technique.


Create the Main Template

At the moment, you can either build a new template in the theme – for example, page-home.php – or you can change the index.php already in attendance in the theme file. If you choose the previous process, then:
  • Build a page
  • Place the page’s template as the template you just fashioned.
  • Go to the interpretation settings in the settings tab.
  • Select the homepage as a motionless one.
  • Choose the page you just fashioned as the homepage.

The template will first contain the header, which you can call using the get_header() method, then the main content, which you will code within the template itself. Lastly, the footer, which you can be included, via the get_footer() method.
The subsequent code demonstrates how you can generate a custom query by means of the wp_query object.

We are using a variable, count to count the figure of items in the catalog. We require this because we will remain only four substance in each line and assign a ‘rightmost‘ class to each fourth list constituent. The ‘rightmost‘ class eliminates any right fringe to the list elements. Alternatively, we could, in our CSS file, use the li:nth-child(4n) selector.

The subsequent code illustrates how we can loop through the posts and insert the content, as required.


Surrounded by the loop, we put in the content in the ordinary WordPress mode, using the $loop wp_query object, of course. The subsequent code displays how we can carry the thumbnail of the project post and interleave it into the template. Make appropriate note of how we use the $count variable to place in the ‘rightmost‘ class on each fourth list ingredient.


Now comes the content part where we require inserting the title, tags, short explanation and fetching the quotation for the post with a custom quotation scheme. Inserting the title is pretty easy, as are the tags. Remember, we formerly created a custom nomenclature by the name of tags.


You will become aware of that we are not by means of the common the_excerpt() process, provided by WordPress. As an alternative, we are essential our own custom technique by adding some filters. The common quotation technique proceeds a better length of quotation than we need. Hence, the custom description. We’re also changing the ‘Continue Reading…’ text added at the end of the default quotation, and replacing it with ‘Read More’. The subsequent snippet serves our purpose. This custom excerpt method comes in handy for profusion of situations.


Step 6 Conclusion

The over technique of creating a multi-layout portfolio is relatively undemanding and uses basic CSS and jQuery tricks to realize the result. Even superior, these techniques can be functional to a variety of projects. Other methods in this lesson, like custom post types, custom taxonomies and adding filters to the passage technique, can be used in various other inventive conducts, as well!

Tab Content Changed using jQuery and WP_Query



Step 1 – New Structural HTML.

We’ll create some extra divs to wrap everything that we’re working with. Place add this following code just above <div id=”wrapper”>: opening tag.
<div id="container">
        <div id="header">
               <h1>MyBlog - WordPress and jQuery together in <em>MyPlugin.</em></h1>
        </div>
               
And we also need to add a final </div> just before the closing </html>

Step 2 – Conditional tags

 Add this code just under our brand new h1 element in index.php.
<?php if(is_home()) {include(TEMPLATEPATH.'/tabbedChangedContent.php'); } ?>
 if(is_home()) is our condition here, so if the page currently being browsed is the home, the include our tabbedChangedContent.php file.

Step 3 – tabbedChangedContent.php (HTML)

Create a new file in our ‘ownTheme’ directory, and name it tabbedChangedContent.php. Type or paste the following into this new file:
<div id="myTabsAndContent">
                       <ul id="myTabsNav">
                               <li><a href="#myRecentArticles">Recent Articles</a></li>
                               <li><a href="#myMonthlyArchives">Monthly Archives</a></li>
                               <li><a href="#mySearchArea">Search</a></li>
                       </ul>
                       <ul id="myTabContent">
                               <li id="myRecentArticles ">
                                      <ul>
                                              <!—RECENT POST GOES HERE -->
                                      </ul>
                               </li>
                               <li id="myMonthlyArchives ">
                                      <ul>
                                              <!-- ARCHIVES PODT GOES HERE -->
                                      </ul>
                               </li>
                               <li id="mySearchArea ">
                                      <!-- SEARCH PAGE GOES HERE -->
                               </li>
                       </ul>
               </div> <!-- div# myTabsAndContent -->
This is just raw HTML without any WordPress or jQuery additions.
#myTabsNav – There are the clickable tabs! We’ve added a href attribute of their corresponding content <li>. Making sure the hrefs match the ID name of their corresponding content list item!
  • #myTabContent – We use a <ul> not unlike WordPress’s sidebars, because it’s easy to style and is essentially a list of content anyway.

Step 4 – myTabbedContent.php (WordPress functions)

So we need to replace the <– –> comments with real content! Now we’ll start with WP_Query(), wp_get_archives(), and a search form.

4.1 – WP_Query()

So cut out the comment tag for our WP_Query, and type the following:
<?php $recentPost = new WP_Query("showposts=5");
        while($recentPost->have_posts()) : $recentPost->the_post();?>
               <li>
                       <a href="<?php the_permalink();?>" title="Link to <?php the_title(); ?>"><?php the_title(); ?></a>
               </li>
<?php endwhile; ?>
Now we’re simply doing, is telling the immanently following loop to show us a list of the 5 latest posts. We can the string within the brackets of WP_Query can be anything… filter by dates, categories, tags, limit, etc.

4.2 – Archives

Now it’s a basic call for a list of monthly archives. And to match the WP_Query section, we only want 5 of them (automatically in descending order). Simply switch the <– WP_ARCHIVES GOES HERE –> in myTabbedContent.php with the following:
               <?php wp_get_archives('type=monthly&limit=5'); ?>

4.3 – Search

We’ll only be using a very simple input and search, using the default search I always use in my own themes. Now we replace the SEARCH PAGE comment with this:
<form method="get" id="mySearchForm" action="<?php bloginfo('home'); ?>">
        <p>
               <input type="text" value="<?php echo wp_specialchars($s, 1); ?>" name="s" id="s" />
               <input type="submit" id="mySearchSubmit" value="Search!" />
        </p>
</form>
Great, so now you should have a new file within the ownTheme directory called myTabbedContent.php, and the conditional tag in index.php.

Step 5 – CSS

At the moment, they are ugly sides. We need to make the page for people without JavaScript enabled first, for graceful degradation. You’ll need some images if you want to make it as pretty just as much as I do. Here is a list of them (right click and save as into the images folder within the ownTheme directory!)
Either type, or paste this massive slab of CSS.
/*------TABS------*/
#container{
        width: 600px;
        margin: 0 auto;
}
h1{
        font-size: 1.3em;
        text-transform: uppercase;
        color: #949494;
        letter-spacing: 1px;
}
#myTabsAndContent ul, #myTabsAndContent li{
        padding: 0
}
ul#myTabsNav{
        float: left;
        width: 200px;
        list-style: none;
}
ul#myTabsNav*:focus {
         outline: none
}
ul#myTabsNav li.active a{
        color: #303030;
}
ul#myTabsNav li a{
        padding: 1em 15px;
        margin: 0 0 1em 0;
        display: block;
        width: 170px;
        text-decoration: none;
        color: #7e7e7e;
        font: 11px/20px Georgia;
        text-transform: uppercase;
}
ul#myTabsNav a:hover{
        color: #0a0a0a
}
ul#myTabsNav {
        margin: 1em 0 0;
        min-height: 180px;
        width: 350px;
        float: left;
        list-style: none;
        padding: 0 25px;
        font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
}
#myTabContent>li{
        width: 350px;
        list-style: none;
        padding: 0 25px 20px 0;
}
#myTabContent li ul li{
        list-style: none;
}
#myTabContent li ul li a{
        display: block;
        border-bottom: 1px solid #e7e7e7;
        padding: 10px 0;
}
form{
        padding: 30px;
}
form input{
        border: 2px solid #cbc6c9;
        border-right: 0;
        padding: 5px;
        margin-right: 0;
        color: #fff;
        font: 16px Georgia, "Times New Roman", Times, serif;
}
#mySearchSubmit{
        border-left: 0;
        border-right: 2px solid #cbc6c9;
        margin-left: 0;
        position: relative;
        left: -3px;
        color: #00416c;
}
#mySearchSubmit:hover{
        background: url(images/tabContentHover.png) no-repeat center;
        color: #003459;
        cursor: pointer;
}

Step 5 – jQuery

Let’s put into words what we need to happen:
  1. Hide all list items we don’t want to see initially, showing only our first content section, the WP_Query section.
  2. Add the class ‘active’ to the first tab, because it’s corresponding section is open.
  3. When a tab is clicked, do the following in order:
    • Eliminate the active class from the currently active tab
    • Include the class active to the tab that has just been clicked
    • Get the href attribute of the a within the clicked tab, and make it our new variable ‘target’
    • Then have the target reveal itself, and the previous showing area hide itself with some simulation
This goes within the jQuery(document).ready(function(){ });, underneath th hero and villain script.
//And our little animated sliding area uptop of the design.
        jQuery('#tabContent>li:gt(0)').hide();
        jQuery('#tabsNav li:first').addClass('active');
        jQuery('#tabsAndContent #tabsNav li').bind('click', function() {
               jQuery('li.active').removeClass('active');
               jQuery(this).addClass('active');
               var target = $('a', this).attr('href');
               jQuery(target).slideDown(400).siblings().slideUp(300);
               return false;
        });

To finish up.

We’ve gone through a lot in this tutorial.
  • WP_Query(); – A great tool for getting content outside the main loop.
  • WordPress conditional tags – unbelievable for further customizing your theme.
  • .bind function – to easily link a function to a specific element with an event.
  • jQuery animation – amazingly easy to implement, and as pretty as a garden of roses.

How to Create Validation Form for Wordpress Comments using jQuery



Step 1 – Download jQuery & the Bassistance.de Validation Plugin

Just download jQuery from  jQuery.com On the first page you will directly see “Download jQuery and a few different downloads. You can download the “Minified and Gzipped” version, this means it’s compressed.
Next we need the jQuery validation plugin, made by bassistance.de. This file contains a few Javascript files, but we only need “jquery.validate.min.js” and compressed for this tutorial.

Step 2 – Uploading files

At this moment you should have 2 files, “jquery.validate.min.js” and “jquery-1.9.1.min.js”, we are going to upload this to our WordPress theme directory.
Because in this tutorial we are using the WordPress theme, literally called “theme_name”, the folder we need is located in /wp-content/themes/theme_name/.
To keep things organized we will create a new directory/folder called “js”, this will be the folder with all the javascript. When you have the directory created, upload the files to the folder we just created. (/wp-content/themes/theme_name/js)

Step 3 – Loading Javascript

Now that we have the javascript uploaded in our directory, we still have to load it into our theme. The javascript should load between the <head> </head> tags. The head tags are located in a php file, that’s located in the theme directory.
So search for “header.php”, this is the file where the top of the theme code is located. Now we have to make sure we add the javascript before these 2 lines:
<?php wp_head(); ?>
</head>
This is how we include a javascript file:
<script src="url/to/javascript" type="text/javascript"></script>
We want things to happen automatically, so it’s best if we use WordPress tags. To display the URL to the template directory you can use this code:
<?php bloginfo('stylesheet_directory'); ?>
So in combination with the code to include the javascript, the final result is:
<script src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="<?php bloginfo('stylesheet_directory'); ?>/js/jquery.validate.min.js"" type="text/javascript"></script>
Now these 2 javascript files will be loaded at every page, and can be used on all WordPress pages using this theme!

Step 4 – Activating Validation

Ok, now it’s time to activate the comment form validation, so go back into the theme directory, and look for /wp-content/themes/theme_name/comments.php
Now, we only need to take a look at the form part of the code! The form starts at line 73, and it looks like this:
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
<?php if ( $user_ID ) : ?>
<p>Logged in<a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Log out »</a></p>
<?php else : ?>
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="25" tabindex="1" />
<label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="25" tabindex="2" />
<label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>
<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="25" tabindex="3" />
<label for="url"><small>Website</small></label></p>
<?php endif; ?>
<!--<p><small><strong>XHTML:</strong> You can use these tags: <code><?php echo allowed_tags(); ?></code></small></p>-->
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />
</p>
<?php do_action('comment_form', $post->ID); ?>
</form>
Now as you can see, the form has an ID element, it’s called “commentform”, we need this name to activate the javascript.
Don’t close this file yet, first switch back to “header.php”, and add these lines below the jquery.validate.min.js
<script type="text/javascript">
jQuery().ready(function() {
// validate the comment form when it is submitted
$("#commentform").validate();
});
</script>
As you can see, the ID of the form is in there, “#commentform” this activates the validation for any form with the id commentform.
Now, when you submit a comment currently and you leave all fields blank it does nothing, it still shows the default WordPress error. In the next step I will show you how to start validation for each field.

Step 5 – Name field validation

Now we start the validation for each field. That’s mean going through telling the validation javascript file what kind of validation is required. The validation javascript is so easy to use; user only needs to enter a few special words or character to start the validation. So let’s we’ll start off with the first field, that’s the required name field, the field looks like this:
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="25" tabindex="1" />
<label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>
We want to make sure the commenter has filled in the field, and if possible make sure at least 6 characters are entered. So simply add class=”important”.
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="25" tabindex="1" class="important" />
<label for="author"><small>Name <?php if ($req) echo "(important)"; ?></small></label></p>
If you hit submit without typing in your name you get “This field is required.” Nice!! So what about if the user doesn’t enter a minimum number of characters?
Well we can simply add that validation by adding minlength=”6″ to the field options:
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="25" tabindex="1" class="important " minlength="6" />
<label for="author"><small>Name <?php if ($req) echo "(important)"; ?></small></label></p>
When you enter something (less then 6 characters) you will see a new message shows up “Please enter at least 6 characters.”. So that works perfectly! Minimum length allows you to set the minimum amount of characters, just replace the number to what you think is necessary.

Step 6 – Mail field validation

Next we will validate the email field, so this is how the field looks like:
<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="25" tabindex="2" />
<label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>
Now we do just the same as the previous step. Well that would be wrong, because aside from the field simply being required, it also has to be a valid email address. Now we know how to set it required by simply adding class=” important”, but how to validate the email?
Just add “email”, so it becomes class=”required_email”, this makes it required and checks for a valid email:
<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="22" tabindex="2" class="required email" />
<label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>
If you try out the email field email, you will notice that it’s says “E-mail address is required.” when submitted, that’s good! And now when you enter something that is not this format: wop@wp.xab it will say “Please enter a valid email address.” so that’s working perfect!

Step 7 – Website field validation

Now we are going to validate the website field? So we are going to validate a URL, it’s just as very easy as previous validations:
<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="25" tabindex="3" />
<label for="url"><small>Website</small></label></p>
At now you could set it required and set a minimum amount of characters. We want a valid URL. We just add another class but this time we name it class=”web_url”:
<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="25" tabindex="3" class="web_url" />
<label for="url"><small>Website</small></label></p>
As you can see it’s very easy thanks to jQuery and the Validation Plugin.

Step 8 – Comment field validation

I would like a minimum and a maximum amount of characters. But first let’s check out the comment field:
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="6"></textarea></p>
We finished step 1, add the required class (class=”important”) to make sure something is typed in the textarea. Now the minimum input text, you remember right? (minlength=”") Now I think at least 6 words need to have been typed. So that would be minlength=”6″, it’s still as easy as that. Now we want to set a maximum. Well the plugin has a solution for that, instead of minimum length just add maximum length plus the amount of words. We want 50 words are enough so add maxlength=”50″.
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4" class="important" minlength="6" maxlength="50"  ></textarea></p>
When we submit the form empty is will say as all other fields “This field is required.”, but if you enter less then 6 characters it says “Please enter at least 6 characters.” and if you enter more then 50 it says “Please enter at least 6 characters.

Step 9 – Form styling

Now we are going style everything so it looks nice and clean, but first I would like to change the label position. As you can see right now, it first shows the “input field” then the “error” and then the “field label”.
I think it should look like this “Field label”, “input field” and then the “error”, to do this we only have to move the label above the html.
<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="25" tabindex="1" class="important" />
<label for="author"><small>Name <?php if ($req) echo "(important)"; ?></small></label></p>
To:
<p><label for="author"><small>Name <?php if ($req) echo "(important)"; ?></small></label>
<input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="25" tabindex="1" /></p>
As you can see the only thing we did was move the <label> above the <input>. When you now refresh your comments page you will see that the text “Name (required) is moved infront of the input field.
So now repeat this step for all input fields, at the end it should look like this:

Now as you can see, all fields have labels, except the comment field, I think it should have a label. So just do the same, and place a label above the input field:
<label for="comment"><small>Comment</small></label></p>
<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
Now it’s time to open the theme CSS file. The CSS file for this theme can be found in “/wp-content/themes/theme_name/style.css”.
Now we’ll make sure to type #commentform .classname, this makes sure only fields between the <form></form> are affected.
#commentform label{
width: 200px;
float:left;
}

#commentform input, #commentform textarea{
border: 1px solid #dbd8d3;
width: 225px;
 
}

Step 10 – Error styling

Now when you hit submit you will see the error messages don’t look very nice. So now we’ll create a good style for error message show.
<label class="error" generated="true" for="author">This field is required.</label>
 
#commentform label.error{
font-size: 11px;
margin-left: 200px;
background: #fbfcda url('images/cancel.png') no-repeat left;
border:1px solid #dbdbd3;
width:209px;
margin-top:4px;
padding-left:20px;
}