Showing posts with label From Scratch. Show all posts
Showing posts with label From Scratch. 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. 

Thursday, March 14, 2013

How to Build A WordPress Theme From Scratch

A developer with some accomplishment in CSS and HTML can calmly actualize their own WordPress capacity to accord their website the adeptness to accommodate a different acquaintance for their visitors. This tutorial will air you through the accomplish of creating your own theme.

Understanding How Capacity Work
Before we can cycle up our sleeves and alpha designing an affair we accept to accept how they plan if it comes to WordPress. Aboriginal you charge to accept that there is an aberration amid capacity and templates if it comes to WordPress. The arrangement book is one or added sets of codes that your affair will alarm upon. Templates, like sidebar.php, header.php, index.php, etc., are alleged aloft by the theme. The affair is the accumulating of arrangement files, images, etc. that tells the visitor's browser how your page(s) will look.
  • style.css
  • rtl.css
  • index.php
  • comments.php
  • front-page.php
  • home.php
  • single.php
  • single-<post-type>.php
  • page.php
  • category.php
  • tag.php
  • taxonomy.php
  • author.php
  • date.php
  • archive.php
  • search.php
  • attachment.php
  • image.php
  • 404.php

Setting the Blueprint of Your Theme
For our affair we are traveling to use an appealing basal blueprint consisting of a header, a footer, the capital agreeable breadth and a sidebar.

Basic blueprint for creating your own WordPress theme

To actualize this you will charge to accessible an argument editor.

If you are application an apparatus like Dreamweaver to actualize your affair again set it on the Cipher appearance for now. You can swell use a basal argument editor like Notepad, eMacs or TextMate.

Now that your argument editor of best is open, blazon the afterward curve of cipher and save it as index.html

<html>
<head>
     <title>Our Very Own WordPress Theme</title>
</head>
     <body>
       <div id="wrapper">
          <div id="header">
             header
          </div> <!-- close header -->
 
       <div id="content">
 
          <div id="main">
             main
          </div> <!-- close main content area-->
 
          <div id="sidebar">
             sidebar
          </div> <!-- close sidebar -->
        </div> <!-- close complete content -->
 
          <div id="footer">
             footer
          </div> <!-- close footer -->
       </div> <!-- close wrapper -->
     </body>
</html>

Notice that in the physique of the HTML book we are application div ids to blueprint our theme. Next, we will actualize the alone arrangement files for each.

Create the Arrangement Files
The aboriginal book we are traveling to actualize is the index.php file.

Open up your argument editor and actualize a new book alleged index.php breadth you will access the afterward code:

<?php get_header(); ?>
 
<div id="main">
<div id="content">
<h1>Main Content Area</h1>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<h4>Posted on <?php the_time('F jS, Y') ?></h4>
<p><?php the_content(__('(more...)')); ?></p>
<hr>
<?php endwhile; else: ?>
<p><?php _e('Sorry, we couldn’t find the post you are looking for.'); ?></p>
<?php endif; ?>
</div>
 
<?php get_sidebar(); ?>
 
</div>
 
<div id="delimiter"></div>
 
<?php get_footer(); ?>

Now you can accomplish some changes actuality if you want. Specifically, the argument that reads Capital Agreeable Breadth amid the Tags and the argument that reads Posted on afterwards the Tag can be customized to something that you would rather see on your blog. You can swell change this after if you want, and back these are arrangement files, the changes will be reflected beyond your absolute blog.

WordPress centralized functions will apprehend this book and accept that the affair is cogent those to go out and grab the files appropriate for your page to attending right. This hotlink will yield you to the WordPress Codex page that describes the functions in abundant greater detail.

Now we can actualize the added php files required.

The Footer File

<html>
<head>
<title>My Theme</title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>This is the header</h1>
</div>

The Footer File

<div id="footer">
<h1>This is the footer</h1>
</div>
 
</div>
< ?php wp_footer(); ? >
</body>
</html>

The Sidebar File

<div id="sidebar">
<h2 class="sidebartitle"><?php _e('Categories'); ?></h2>
<ul>
<?php wp_list_cats('sort_column=name&optioncount=1&hierarchical=0'); ?>
</ul>
 
<h2 class="sidebartitle"><?php _e('Archives'); ?></h2>
<ul class="list-archives">
<?php wp_get_archives('type=monthly'); ?>
</ul>
</div>

Now the aftereffect will go advanced and grab the Categories and affectation them as able-bodied as the Archives that will be displayed monthly.

Where is the Main.php file?
No, I didn't overlook a part. The capital agreeable breadth will be busy with the blog posts themselves so we won't be creating a main.php. We do charge to actualize a style.css book though. So let's do that.

body {
    text-align: center;
}
 
#wrapper {
    display: block;
    border: 1px #000 solid;
    width:90%;
    margin:0px auto;
}
 
#header {
    border: 2px #000 solid;
}
 
#content {
    width: 75%;
    border: 2px #000 solid;
    float: left;
}
 
#sidebar {
    width: 23%;
    border: 2px #000 solid;
    float: right;
}
 
#delimiter {
    clear: both;
}
 
#footer {
    border: 2px #000 solid;
}
 
.title {
    font-size: 11pt;
    font-family: arial;
    font-weight: bold;
}


We wouldn't apprehend this to be the accomplished artifact on your blog. In the next allotment of this alternation we will attend at abacus a logo and some added elements to dress up your new theme.