Custom Code

<node>CUSTOM CODING
<node>Disable auto updates
<node>Disable site
<node>EXTERNAL PHP
<node>Hacks
<node>footer changes
<node>Header Change
<node>New user
<node>is logged in
<node>Merging admins
<node>Protect Login Screen
<node>redirect
<node>Codects
<node>database access
<node>domain change
<node>Embed wordpress page
<node>MEMBERlogin
<node>Redirect
<node>database
<node>get_row
<node>MergeDatabases
<node>minimum permissions
<node>New subject
<node>notes
<node>plugin
<node>backupWordpress
<node>Contact form
<node>shortcodes
<node>WIDGET
<node>example
<node>new area
<node>saved info
<node>simple one

<Treepad version 3.0>
dt=
<node>CUSTOM CODING
0
accepted
    
If you are getting to the point where the code in your theme's functions.php is starting to overwhelm you I would definitely say you are ready to consider splitting it up into multiple files. I tend to do that almost by second nature at this point.
Use Include Files in your Theme's functions.php File
I create a subdirectory called "includes" under my theme directory and segment my code into include files organized by what makes sense to me at the time (which means I'm constantly refactoring and moving code around as a site evolves.) I also rarely put any real code in functions.php; everything goes in the include files; just my preference.
Just to give you an example here's my test install that I use to test my answers to questions here on WordPress Answers. Every time I answer a question I keep the code around in case I need it again. This isn't exactly what you'll do for a live site but it shows the mechanics of splitting up the code:
require_once('includes/null-meta-compare.php');
require_once('includes/older-examples.php');
require_once('includes/wp-admin-menu-classes.php');
<end node> 5P9i0s8y19Z
dt=
<node>Disable auto updates
1
Example Coding Magic: Turn Off Automatic Updates
Auto updates have been a part of WordPress since version 3.7. Not everyone likes this feature; many would like to turn it off. All you need to do is add this line of code to your
wp-config.php file.
1./* Disable WordPress automatic updates */
.2.define( 'WP_AUTO_UPDATE_CORE', false );
<end node> 5P9i0s8y19Z
dt=
<node>Disable site
1
In the header.php file of genisis
<?php
if(!is_user_logged_in()){
echo "This site is under construction"; exit;
}
<end node> 5P9i0s8y19Z
dt=
<node>EXTERNAL PHP
1
home
| photos
|     login
  
Integrating WP in external PHP pages
24
Jun
I have several external pages that use the WP theme engine to wrap the content. I use the method found here, which worked great under WordPress 2.9.2. After upgrading to WP 3.0, these pages no longer worked as expected but instead generated 404s; it turns out the fix is rather simple.
The code to include the WP theme in external pages used to look like this:
< ?php 'OLD METHOD
require('./wp-blog-header.php');
get_header();
?>
<h2>This is the external content.</h2>
< ?php
get_sidebar();
get_footer();
?>
The newest version of WP merged the old WordPress Multi-User (WPMU) and the standalone version of WordPress. Since this merger, the new way to include WP in external pages is to change the require() statement to pull in wp-load.php (instead of wp-blog-header.php) like this:
< ?php
require('./wp-load.php');
get_header();
?>
<h2>This is the external content.</h2>
< ?php
get_sidebar();
get_footer();
?>
Now your external pages work just like they used to! I found the answer on a BBPress forum post from nine months ago.
This entry was posted on Thursday, June 24th, 2010 at 11:00 am and is filed under Web Development, WordPress. It was tagged with the following tags: php, web, WordPress. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
<end node> 5P9i0s8y19Z
dt=
<node>Hacks
1
new user: http://www.wpbeginner.com/wp-tutorials/how-to-add-an-admin-user-to-the-wordpress-database-via-mysql/
<end node> 5P9i0s8y19Z
dt=
<node>footer changes
2
in the themes function.php add:
remove_action( 'genesis_footer', 'genesis_do_footer' );
add_action( 'genesis_footer', 'sp_custom_footer' );
function sp_custom_footer() {
    ?>
    <p>Copyright 2015 – Software Web Design</p>
    <?php
}
<?php
/**
* Genesis Framework.
*
* WARNING: This file is part of the core Genesis Framework. DO NOT edit this file under any circumstances.
* Please do all modifications in the form of a child theme.
*
* @package Genesis\Templates
* @author  StudioPress
* @license GPL-2.0+
* @link    http://my.studiopress.com/themes/genesis/
*/
genesis_structural_wrap( 'site-inner', 'close' );
echo '</div>'; //* end .site-inner or #inner
add_filter( 'genesis_footer_creds_text', 'custom_footer_creds_text' );
function custom_footer_creds_text() {
    echo '<div class="creds"><p>';     echo 'Copyright © ';     echo date('Y');     echo '·Built by <a href="http://www.kblegacydesigns.com">Kb Legacy Designs</a> & <a href="http://www.softwarewebdesign.com">Software Web Design</a> · ';     echo '</p></div>'; }
do_action( 'genesis_before_footer' );
  
do_action( 'genesis_footer' );

do_action( 'genesis_after_footer' );

echo '</div>'; //* end .site-container or #wrap
do_action( 'genesis_after' );
wp_footer(); //* we need this for plugins
?>
</body>
</html>
Footer
Make Sure you have ftp access just in case because I brought the site down using editor
Code snippets should be placed in your child theme's functions.php file.
For Beginners, you may wish to use the Simple Edits plugin to edit the footer from the admin area.
For Intermediate users who need more control over the appearace of the footer –
Below is the code to customize the Return to Top of Page text on your site:
/** Customize the return to top of page text */add_filter( 'genesis_footer_backtotop_text', 'custom_footer_backtotop_text' ); function custom_footer_backtotop_text($backtotop) {     $backtotop = '[footer_backtotop text="Return to Top"]';     return $backtotop; }
Below is the code to customize the Credits text on your site:
/* Customize the credits exmpl1*/
add_filter( 'genesis_footer_creds_text', 'custom_footer_creds_text' ); function custom_footer_creds_text() {     echo '<div class="creds"><p>';     echo 'Copyright © ';     echo date('Y');     echo ' · <a href="http://mydomain.com">My Custom Link</a> · Built on the <a href="http://www.studiopress.com/themes/genesis" title="Genesis Framework">Genesis Framework</a>';     echo '</p></div>'; }
//Change  footer credits exmpl 2
add_filter( 'genesis_footer_creds_text', 'custom_footer_creds_text' );
function custom_footer_creds_text() {
    echo '<div class="creds"><p>';     echo 'Copyright © ';     echo date('Y');     echo ' · <a href="http://kblegacy.com">KB Legacy</a> · Built by KB Legacy Designs';     echo '</p></div>'; }
Below is the code to customize the entire footer text on your site:
/** Customize the entire footer */remove_action( 'genesis_footer', 'genesis_do_footer' ); add_action( 'genesis_footer', 'custom_footer' ); function custom_footer() {     ?>     <p>© Copyright 2012 <a href="http://mydomain.com/">My Domain</a> · All Rights Reserved · Powered by <a href="http://wordpress.org/">WordPress</a> · <a href="http://mydomain.com/wp-admin">Admin</a></p>     <?php }
<end node> 5P9i0s8y19Z
dt=
<node>Header Change
2
<?php
/*  Template Name: Include Page */
add_action('genesis_meta', 'add_head');
function add_head() {
    include("wpHeaderInclude.php");
}

Outreach Child Theme: wpHeaderInclude.php
<link rel="stylesheet" href="<?php echo includes_url(); ?>/js/lightbox/lightbox.css" type="text/css" media="screen" >
<script type="text/javascript" src="<?php echo includes_url(); ?>/js/lightbox/lightbox.js"></script>
Just add your lightbox folder to the include/js folder
=====================================================
I actually found how to do it, it's pretty straight forward:
1/ Register a function to be executed when the wp_head action fires:
add_action('wp_head', 'my_function');
2/ Make the function echo whatever you want in the header:
function my_function()
{
<link rel="stylesheet" href="<?php echo includes_url(); ?>/js/lightbox/lightbox.css" type="text/css" media="screen" >
echo '<meta name="robots" content="noindex, nofollow">';
}
Using this trick for the Facebook Like plugin, thanks to the smart Add Your Own Headers plugin that showed me pointers.
<end node> 5P9i0s8y19Z
dt=
<node>New user
2
REQUIRES 3 INSERTS
INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Syed Balkhi', 'test@yourdomain.com', 'http://www.wpbeginner.com/', '2011-06-07 00:00:00', '', '0', 'Syed Balkhi');
2    
3    
4    INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
5    
6    
7    INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
wp_w3q1o7u0_usermeta
WPBeginner» Blog» Tutorials» How to Add an Admin User to…
How to Add an Admin User to the WordPress Database via MySQL
Last updated on November 25th, 2014 by Editorial Staff
Share This Article
101
Follow WPBeginner on YouTube
How to Add an Admin User to the WordPress Database via MySQL
Few days ago, we ran into an issue where a user’s site got hacked and their admin account was deleted from the database. This locked them out of their site without any other entry. We went in to the phpMyAdmin and created a new admin user to grant them access. In this article, we will show you a step by step guide on how to create an admin user in WordPress Database via MySQL.
Note: You should always make a backup of your database before performing any MySQL edits. This tutorial requires basic understanding of how phpMyAdmin works.
Video Tutorial
If you don’t like the video or need more instructions, then continue reading.
First, you need to login to phpMyAdmin and locate your WordPress database. (Below is a screenshot of a HostGator cPanel)
cPanel phpMyAdmin
Once you are in, we will be making changes to the wp_users and wp_usermeta tables. Lets go ahead and click on wp_users table.
phpMyAdmin wp_users table
We need to insert our new admin user’s information, so click on the Insert tab like it shows in the image above. In the insert form, add the following:
    ID – pick a number (in our example, we will use the number 4).
    user_login – insert the username you want to use to access the WordPress Dashboard.
    user_pass – add a password for this username. Make sure to select MD5 in the functions menu (Refer to the screenshot below).
    user_nicename – put a nickname or something else that you would like to refer yourself as.
    user_email – add the email you want to associate with this account.
    user_url – this would be the url to your website.
    user_registered – select the date/time for when this user is registered.
    user_status – set this to 0.
    display_name – put the name you like to display for this user on the site (it can be your user_nicename value as well).
    Click on the Go Button
phpMyAdmin Insert values in wp_users table
Next we are going to have to add the values to wp_usermeta table. Click on the wp_usermeta table and then click on the Insert tab just like the previous step. Then add the following information to the insert form:
    unmeta_id – leave this blank (it will be auto-generated)
    user_id – this will be the id of the user you created in the previous step. Remember we picked 4.
    meta_key – this should be wp_capabilities
    meta_value – insert this: a:1:{s:13:"administrator";s:1:"1";}
Insert another row with the following information:
    unmeta_id – leave this blank (it will be auto-generated)
    user_id – this will be the id of the user you created in the previous step. Remember we picked 4.
    meta_key – this should be wp_user_level
    meta_value – 10
Then click on the Go button, and you have created yourself a new username. Now you should be able to login to your wp-admin with the username and password you specified for this user. Once logged in, click on Users and edit the username you just created. Go down and click on the Save button (you don’t have to change anything). This will allow WordPress to go through and add some more information and clean-up the user we just added.
SQL query
For developers who want to speed this process up, you can simply drop this SQL query in your database.
1    INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Syed Balkhi', 'test@yourdomain.com', 'http://www.wpbeginner.com/', '2011-06-07 00:00:00', '', '0', 'Syed Balkhi');
2    
3    
4    INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
5    
6    
7    INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
Remember to change the databasename to the database you are working with. Also don’t forget to change the appropriate values.
About the Editorial Staff
Editorial Staff at WPBeginner is a team of WordPress lovers led by Syed Balkhi. Page maintained by Syed Balkhi.
More on WPBeginner Right Now
    How to Easily Create a Responsive WordPress Slider with Soliloquy
    How to Easily Create a Responsive WordPress Slider with Soliloquy
    How We Increased Our Organic Search Traffic By Using HitTail
    How We Increased Our Organic Search Traffic By Using HitTail
    WordPress Custom Fields 101: Tips, Tricks, and Hacks
    WordPress Custom Fields 101: Tips, Tricks, and Hacks
    How to Get Google’s Verified Authorship for your WordPress Blog
    How to Get Google’s Verified Authorship for your WordPress Blog
WPBeginner's WordPress Training Videos Free
WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »
Join over 130,000 WordPress Users
who get fresh content from WPBeginner!
<end node> 5P9i0s8y19Z
dt=
<node>is logged in
1
<?php
if(!is_user_logged_in()){
echo "This site is under construction"; exit;
}
<end node> 5P9i0s8y19Z
dt=
<node>Merging admins
1
Add this to the mystuff.php of the non wordpress admin FROM THE WINDSORSEVERANCESTORAGE.COM
session_start();
include("config.php");
require_once("../wp-load.php");
if(!is_user_logged_in() && $bypass!=true){
echo "This site is under construction"; exit;
} else $wordpress=true;
if($wordpress==false){
    $db = mysql_pconnect($server, $user,$password);
    if (!$db){
        echo 'Error: Could not connect to database.  Please try again later.'; exit;
    }
    mysql_select_db($database);
    if($pageLevel=='')$pageLevel=3;
    if($LEVEL<$pageLevel && $bypass!=true){
        echo "<body onload=setTimeout(\"location.href='LoginScreen.php'\",2000)>";
        echo "You need to login with more security.<p>Click <a href='LoginScreen.php'>here</a> to continue.";$_SESSION['LEVEL']='';exit;
    }
}else $_SESSION['LEVEL']=10;
<end node> 5P9i0s8y19Z
dt=
<node>Protect Login Screen
1
This is done near the top in both files
in the index.php of the root/wp-admin folder add:
if($_GET["SWD"]!="") setcookie("SWD_ADMIN","swd", time()+(60*60*24*30),"/");
in the root folder wp-login.php add:
if($_COOKIE["SWD_ADMIN"]!="swd"){ echo "You have been terminated"; exit; }
<end node> 5P9i0s8y19Z
dt=
<node>redirect
1
add_action( 'template_redirect', 'restrictPage_blah', 100 );
function restrictPage_blah() {
if( ! is_user_logged_in() && is_page('restrictedPage') )
{
wp_redirect( 'http://www.google.com' );
    exit;
}
}
<end node> 5P9i0s8y19Z
dt=
<node>Codects
1
<?php
require_once("../wp-load.php");
require_once("swdFunctions.php");
function current_session(){
   $sessionid =$_COOKIE["MYCOOKIE"];//$_SESSION["MYSESSION"];
    if($sessionid==""){
      $sessionid=strtotime(date("Y-m-d H:i:s")); setcookie("MYCOOKIE",$sessionid,time()+60*60*24*300);
    }
    return $sessionid;
}
get_header();
include(get_site_url()."/swd/mdropdown.php");
?>
<div id="content-full" class="grid col-940">
</div><!– end of #content-full –>
<?php get_footer(); ?>
<end node> 5P9i0s8y19Z
dt=
<node>database access
2
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php'; // THIS MAY BE THE ONLY LINE YOU MAY NEED
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
// $wpdb is available, do stuff
<end node> 5P9i0s8y19Z
dt=
<node>domain change
2
UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com','http://www.new-domain.com');
UPDATE whs_posts SET guid = replace(guid, 'http://www.softwarewebsecure.com/WINDSORHAIR','http://new.windsorhairshoppe.com');
<end node> 5P9i0s8y19Z
dt=
<node>Embed wordpress page
2
From the swinterTmpl.php from Storage
include(includes_url()."storageLeaseForm.php?WPLOGIN=".STORAGE_MEMBER."&site1=".urlencode(site_url()));
            $include1 = get_pages('include=62'); $content = apply_filters('the_content',$include1[0]->post_content); echo $content;
            //echo includes_url()."storageLeaseForm.php?site1=".urlencode(site_url());
            break;
ID: page/post ID (int)
?post_author: author ID (string)
?post_date: time-date string (YYYY-MM-DD HH:MM:SS), e.g., "2012-10-15 01:02:59"
?post_date_gmt: time-date string
?post_content: HTML (string)
?post_title
?post_excerpt: HTML (string)
?post_status: (publish|inherit|pending|private|future|draft|trash)
?comment_status: closed/open
?ping_status: (closed|open)
?post_password
?post_name: slug for page/post
?to_ping
?pinged
?post_modified: time-date string
?post_modified_gmt: time-date string
?post_content_filtered
?post_parent: parent ID (int)
?guid: URL
?menu_order: (int)
?post_type: (page|post|attachment)
?post_mime_type
?comment_count: number of comments (string)
?filter
All values are strings unless otherwise shown as (int).
<end node> 5P9i0s8y19Z
dt=
<node>MEMBERlogin
2
using the index.php
<?php
session_start();
define('DARNELL_MEMBER', $_SESSION["DARNELL"]);
//echo "shoot";exit;
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
<end node> 5P9i0s8y19Z
dt=
<node>Redirect
2
[mix wordpress with non-wordpress site]
$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parse = parse_url($actual_link);
//echo "dog–".$server1;
if($parse['host']=="new.angeldesignsbydenise.com"){
   define('WP_USE_THEMES', true);
// Loads the WordPress Environment and Template
   require( dirname( __FILE__ ) . '/wp-blog-header.php' );
   exit;
}
<end node> 5P9i0s8y19Z
dt=
<node>database
1
[MULTIPLE RECORDS]
$rows=$wpdb->get_results($query);$num=$wpdb->num_rows;
foreach ( $rows as $row ) {
    if($cnt>$defaultField){
        $dis.="\n</td></tr></table><td width=175><table><tr><td><b>Member</b><td><b>Year<b></td>\n";$cnt=0;
    }
   $donationid=$row->donationid;
    $last_name=$row->last_name;
    $last_name=ShortenString($last_name);
    $first_name=$row->first_name;
    $first_name=ShortenString($first_name);
    $authcode=$row->authcode;
    $datefill=$row->datefill;
    $timelapse=(int)((strtotime(date("Y-m-d"))-strtotime($datefill))/$yearlapse);
    if($timelapse==0)$timelapse="NEW";
//REPORT FORMAT here
        if($authcode=="YES"){
            $dis.="<tr><td align=right>Anonymous</td><td width=20 style='text-align:center;'>$timelapse</td></tr>\n";
        }else{
            $dis.="<tr><td align=right>$first_name $last_name</td><td width=20 style='text-align:center;'>$timelapse</td></tr>\n";   // <td class=view>$first_name</td>    <td class=view>$address</td>    <td class=view>$city</td>    <td class=view>$state</td>    <td class=view>$zip</td>    <td class=view>$phone</td>    <td class=view>$email</td>    <td class=viewnumber align=right>$pay_interval</td>    <td class=view>$pay_option</td>    <td class=viewnumber align=right>$amount</td>    <td class=view>$datefill</td>    <td class=view>$responsecode</td>    <td class=viewnumber align=right>$subscriptionid</td>    <td class=view>$reasoncode</td>    <td class=view>$reasontext</td>    <td class=view>$authcode</td>    <td class=view>$avscode</td>    <td class=view>$cardType</td>    <td class=view>$cardnum</td>    <td class=view>$csc</td>    <td class=view>$month</td>    <td class=viewnumber align=right>$year</td>";
        }
    $cnt++;
}
SELECT Generic Results
Generic, mulitple row results can be pulled from the database with get_results. The function returns the entire query result as an array, or NULL on no result. Each element of this array corresponds to one row of the query result and, like get_row, can be an object, an associative array, or a numbered array.
<?php $wpdb->get_results('query', output_type); ?>
query
    (string) The query you wish to run. Setting this parameter to null will return the data from the cached results of the previous query.
output_type
    One of four pre-defined constants. Defaults to OBJECT. See SELECT a Row and its examples for more information.
        OBJECT – result will be output as a numerically indexed array of row objects.
        OBJECT_K – result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
        ARRAY_A – result will be output as an numerically indexed array of associative arrays, using column names as keys.
        ARRAY_N – result will be output as a numerically indexed array of numerically indexed arrays.
Since this function uses the '$wpdb->query()' function all the class variables are properly set. The results count for a 'SELECT' query will be stored in $wpdb->num_rows.
[UPDATE OR DELETE]
Run Any Query on the Database
The query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function (see below), however, for SELECT queries.
<?php $wpdb->query('query'); ?>
query
    (string) The SQL query you wish to execute.
The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).
<end node> 5P9i0s8y19Z
dt=
<node>get_row
2
SELECT a Row
To retrieve an entire row from a query, use get_row. The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns OBJECT holding NULL if no result is found, consider this when using the returned value in arguments, see example below
<?php $wpdb->get_row('query', output_type, row_offset); ?>
query
(string) The query you wish to run.
output_type
One of three pre-defined constants. Defaults to OBJECT.
¦OBJECT – result will be output as an object.
¦ARRAY_A – result will be output as an associative array.
¦ARRAY_N – result will be output as a numerically indexed array.
row_offset
(integer) The desired row (0 being the first). Defaults to 0.
Examples
Get all the information about Link 10.
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10");
The properties of the $mylink object are the column names of the result from the SQL query (in this example all the columns from the $wpdb->links table, but you could also query for specific columns only).
echo $mylink->link_id; // prints "10"
In contrast, using
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);
would result in an associative array:
echo $mylink['link_id']; // prints "10"
and
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_N);
would result in a numerically indexed array:
echo $mylink[1]; // prints "10"
If there is no record with ID 10 in the links table, null will be returned. The following would then be false:
if ($mylink != null) {
  // do something with the link
  return true;
} else {
  // no link found
  return false;
}
<end node> 5P9i0s8y19Z
dt=
<node>MergeDatabases
2
http://wordpress.stackexchange.com/questions/94018/merging-two-wp-posts-tables-while-avoiding-duplicates
Import the new table as wp_posts_2, then join them and delete all duplicates based on post_content; then merge the two tables.
The following SQL query (untested!) should give the posts from the new table to be deleted:
SELECT wp2.* FROM wp_posts_2 as wp2 LEFT JOIN wp_posts as wp ON wp2.post_content = wp.post_content WHERE wp2.post_content = wp.post_content
So, you can delete the entries with this query (also untested):
DELETE wp_posts_2.* LEFT JOIN wp_posts as wp ON wp_posts_2.post_content = wp.post_content WHERE wp_posts_2.post_content = wp.post_content
Then merge the two tables.
<end node> 5P9i0s8y19Z
dt=
<node>minimum permissions
2
Below is an example of the minimum privileges a database user needs to have. Other database permissions are regarded as “extra” privileges that in most cases are not needed. A typical WordPress user should be granted the following database privileges only:
The official documentation says to give the user all privs. Others suggest that you can restrict it to
SELECT
•INSERT
•UPDATE
•DELETE
•CREATE
•ALTER
•INDEX
•DROP optional
Plugins etc can though call any statement they want so you would have to thoroughly test
Data:
    SELECT
    INSERT
    UPDATE
Example of How to Grant Access Privileges
If you are upgrading WordPress, the above database permissions might not suffice between versions, WordPress might need to make further changes to the database. In this case, if you are only upgrading to the latest version of WordPress, add the below privileges to the WordPress database user:
Structure:
    CREATE
    ALTER
NOTE: Some plugins might require additional database privileges such as CREATE, DROP or DELETE and in those cases these privileges should be granted.
<end node> 5P9i0s8y19Z
dt=
<node>New subject
2
<end node> 5P9i0s8y19Z
dt=
<node>notes
2
Interfacing With the Database
WordPress provides a class of functions for all database manipulations. The class is called wpdb and is loosely based on the ezSQL class written and maintained by Justin Vincent.
Using the $wpdb Object
Methods in the wpdb() class should not be called directly.
WordPress provides a global variable, $wpdb, which is an instantiation of the class already set up to talk to the WordPress database. Always use the global $wpdb variable. (Remember to globalize $wpdb before using it in any custom functions.)
The $wpdb object can be used to read data from any table in the WordPress database (such as custom plugin tables), not just the standard tables that WordPress creates. For example to SELECT some information from a custom table called "mytable", you can do the following. $myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );
The $wpdb object can talk to any number of tables, but only one database: the WordPress database. In the rare case you need to connect to another database, you will have to instantiate your own object from the wpdb class with the appropriate connection details. For extremely complicated setups with many databases, consider using hyperdb instead. Run Any Query on the Database
The query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function (see below), however, for SELECT queries.
<?php $wpdb->query('query'); ?>
query
(string) The SQL query you wish to execute.
The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).
Note: As with all functions in this class that execute SQL queries, you must SQL escape all inputs (e.g., wpdb->escape($user_entered_data_string)). See the section entitled Protect Queries Against SQL Injection Attacks below.
Examples
Delete the 'gargle' meta key and value from Post 13. (We'll add the 'prepare' method to make sure we're not dealing with an illegal operation or any illegal characters):
$wpdb->query(
    $wpdb->prepare(
        "
                DELETE FROM $wpdb->postmeta
         WHERE post_id = %d
         AND meta_key = %s
        ",
            13, 'gargle'
        )
);
Performed in WordPress by delete_post_meta().
Set the parent of Page 15 to Page 7.
$wpdb->query(
    "
    UPDATE $wpdb->posts
    SET post_parent = 7
    WHERE ID = 15
        AND post_status = 'static'
    "
);
SELECT a Variable
The get_var function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found.
<?php $wpdb->get_var('query',column_offset,row_offset); ?>
query
(string) The query you wish to run. Setting this parameter to null will return the specified variable from the cached results of the previous query.
column_offset
(integer) The desired column (0 being the first). Defaults to 0.
row_offset
(integer) The desired row (0 being the first). Defaults to 0.
Examples
Retrieve and display the number of users.
<?php
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );
echo "<p>User count is {$user_count}</p>";
?>
Retrieve and display the sum of a Custom Field value.
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'miles';
$allmiles = $wpdb->get_var( $wpdb->prepare(
    "
        SELECT sum(meta_value)
        FROM $wpdb->postmeta
        WHERE meta_key = %s
    ",
    $meta_key
) );
echo "<p>Total miles is {$allmiles}</p>";
?>
SELECT a Row
To retrieve an entire row from a query, use get_row. The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns OBJECT holding NULL if no result is found, consider this when using the returned value in arguments, see example below.
<?php $wpdb->get_row('query', output_type, row_offset); ?>
query
(string) The query you wish to run.
output_type
One of three pre-defined constants. Defaults to OBJECT.
¦OBJECT – result will be output as an object.
¦ARRAY_A – result will be output as an associative array.
¦ARRAY_N – result will be output as a numerically indexed array.
row_offset
(integer) The desired row (0 being the first). Defaults to 0.
Examples
Get all the information about Link 10.
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10");
The properties of the $mylink object are the column names of the result from the SQL query (in this example all the columns from the $wpdb->links table, but you could also query for specific columns only).
echo $mylink->link_id; // prints "10"
In contrast, using
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);
would result in an associative array:
echo $mylink['link_id']; // prints "10"
and
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_N);
would result in a numerically indexed array:
echo $mylink[1]; // prints "10"
If there is no record with ID 10 in the links table, null will be returned. The following would then be false:
if ($mylink != null) {
  // do something with the link
  return true;
} else {
  // no link found
  return false;
}
SELECT a Column
To SELECT a column, use get_col. This function outputs a one dimensional array. If more than one column is returned by the query, only the specified column will be returned by the function, but the entire result is cached for later use. Returns an empty array if no result is found.
<?php $wpdb->get_col('query',column_offset); ?>
query
(string) the query you wish to execute. Setting this parameter to null will return the specified column from the cached results of the previous query.
column_offset
(integer) The desired column (0 being the first). Defaults to 0.
Examples
For this example, assume the blog is devoted to information about automobiles. Each post describes a particular car (e.g. 1969 Ford Mustang), and three Custom Fields, manufacturer, model, and year, are assigned to each post. This example will display the post titles, filtered by a particular manufacturer (Ford), and sorted by model and year.
The get_col form of the wpdb Class is used to return an array of all the post ids meeting the criteria and sorted in the correct order. Then a foreach construct is used to iterate through that array of post ids, displaying the title of each post. Note that the SQL for this example was created by Andomar.
<?php
$meta_key1        = 'model';
$meta_key2        = 'year';
$meta_key3        = 'manufacturer';
$meta_key3_value    = 'Ford';
$postids=$wpdb->get_col( $wpdb->prepare(
    "
    SELECT      key3.post_id
    FROM        $wpdb->postmeta key3
    INNER JOIN  $wpdb->postmeta key1
                ON key1.post_id = key3.post_id
                AND key1.meta_key = %s
    INNER JOIN  $wpdb->postmeta key2
                ON key2.post_id = key3.post_id
                AND key2.meta_key = %s
    WHERE       key3.meta_key = %s
                AND key3.meta_value = %s
    ORDER BY    key1.meta_value, key2.meta_value
    ",
    $meta_key1,
    $meta_key2,
    $meta_key3,
    $meta_key3_value
) );
if ( $postids )
{
    echo "List of {$meta_key3_value}(s), sorted by {$meta_key1}, {$meta_key2}";
    foreach ( $postids as $id )
    {
        $post = get_post( intval( $id ) );
        setup_postdata( $post );
        ?>
        <p>
            <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
                <?php the_title(); ?>
            </a>
        </p>
        <?php
    }
}
?>
This example lists all posts that contain a particular custom field, but sorted by the value of a second custom field.
<?php
// List all posts with custom field Color, sorted by the value of custom field Display_Order
// does not exclude any 'post_type'
// assumes each post has just one custom field for Color, and one for Display_Order
$meta_key1 = 'Color';
$meta_key2 = 'Display_Order';
$postids = $wpdb->get_col( $wpdb->prepare(
    "
    SELECT      key1.post_id
    FROM        $wpdb->postmeta key1
    INNER JOIN  $wpdb->postmeta key2
                ON key2.post_id = key1.post_id
                AND key2.meta_key = %s
    WHERE       key1.meta_key = %s
    ORDER BY    key2.meta_value+(0) ASC
    ",
        $meta_key2,
    $meta_key1
) );
if ( $postids )
{
    echo "List of {$meta_key1} posts, sorted by {$meta_key2}";
    foreach ( $postids as $id )
    {
        $post = get_post( intval( $id ) );
        setup_postdata( $post );
        ?>
        <p>
            <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
                <?php the_title(); ?>
            </a>
        </p>
        <?php
    }
}
?>
SELECT Generic Results
Generic, mulitple row results can be pulled from the database with get_results. The function returns the entire query result as an array, or NULL on no result. Each element of this array corresponds to one row of the query result and, like get_row, can be an object, an associative array, or a numbered array.
<?php $wpdb->get_results('query', output_type); ?>
query
(string) The query you wish to run. Setting this parameter to null will return the data from the cached results of the previous query.
output_type
One of four pre-defined constants. Defaults to OBJECT. See SELECT a Row and its examples for more information.
¦OBJECT – result will be output as a numerically indexed array of row objects.
¦OBJECT_K – result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
¦ARRAY_A – result will be output as an numerically indexed array of associative arrays, using column names as keys.
¦ARRAY_N – result will be output as a numerically indexed array of numerically indexed arrays.
Since this function uses the '$wpdb->query()' function all the class variables are properly set. The results count for a 'SELECT' query will be stored in $wpdb->num_rows.
Examples
Get the IDs and Titles of all the Drafts by User 5 and echo the Titles.
$fivesdrafts = $wpdb->get_results(
    "
    SELECT ID, post_title
    FROM $wpdb->posts
    WHERE post_status = 'draft'
        AND post_author = 5
    "
);
foreach ( $fivesdrafts as $fivesdraft )
{
    echo $fivesdraft->post_title;
}
Get all information on the Drafts by User 5.
<?php
$fivesdrafts = $wpdb->get_results(
    "
    SELECT *
    FROM $wpdb->posts
    WHERE post_status = 'draft'
        AND post_author = 5
    "
);
if ( $fivesdrafts )
{
    foreach ( $fivesdrafts as $post )
    {
        setup_postdata( $post );
        ?>
        <h2>
            <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink: <?php the_title(); ?>">
                <?php the_title(); ?>
            </a>
        </h2>
        <?php
    }
    else
    {
        ?>
        <h2>Not Found</h2>
        <?php
    }
}
?>
INSERT rows
Insert a row into a table.
<?php $wpdb->insert( $table, $data, $format ); ?>
table
(string) The name of the table to insert data into.
data
(array) Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
format
(array|string) (optional) An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
Possible format values: %s as string; %d as decimal number; and %f as float.
After insert, the ID generated for the AUTO_INCREMENT column can be accessed with:
$wpdb->insert_idThis function returns false if the row could not be inserted.
Examples
Insert two columns in a row, the first value being a string and the second a number:
$wpdb->insert(
    'table',
    array(
        'column1' => 'value1',
        'column2' => 123
    ),
    array(
        '%s',
        '%d'
    )
);
UPDATE rows
Update a row in the table. Returns false if errors, or the number of rows affected if successful.
<?php $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); ?>
table
(string) The name of the table to update.
data
(array) Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
where
(array) A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
format
(array|string) (optional) An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data.
where_format
(array|string) (optional) An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where.
Possible format values: %s as string; %d as decimal number and %f as float. If omitted, all values in $where will be treated as strings.
This function returns the number of rows updated, or false if there is an error.
Examples
Update a row, where the ID is 1, the value in the first column is a string and the value in the second column is a number:
$wpdb->update(
    'table',
    array(
        'column1' => 'value1',    // string
        'column2' => 'value2'    // integer (number)
    ),
    array( 'ID' => 1 ),
    array(
        '%s',    // value1
        '%d'    // value2
    ),
    array( '%d' )
);
Attention: %d can't deal with comma values – if you're not using full numbers, use string/%s.
Protect Queries Against SQL Injection Attacks
For a more complete overview of SQL escaping in WordPress, see database Data Validation. That Data Validation article is a must-read for all WordPress code contributors and plugin authors.
Briefly, though, all data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks. This can be conveniently done with the prepare method, which supports both a sprintf()-like and vsprintf()-like syntax.
Please note: As of 3.5, wpdb::prepare() enforces a minimum of 2 arguments. [more info]
<?php $sql = $wpdb->prepare( 'query' , value_parameter[, value_parameter … ] ); ?>
query
(string) The SQL query you wish to execute, with %s and %d placeholders. Any other % characters may cause parsing errors unless they are escaped. All % characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%.
value_parameter
(int|string|array) The value to substitute into the placeholder. Many values may be passed by simply passing more arguments in a sprintf()-like fashion. Alternatively the second argument can be an array containing the values as in PHP's vsprintf() function. Care must be taken not to allow direct user input to this parameter, which would enable array manipulation of any query with multiple placeholders. Values must not already be SQL-escaped.
Examples
Add Meta key => value pair "Harriet's Adages" => "WordPress' database interface is like Sunday Morning: Easy." to Post 10.
$metakey    = "Harriet's Adages";
$metavalue    = "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare(
    "
        INSERT INTO $wpdb->postmeta
        ( post_id, meta_key, meta_value )
        VALUES ( %d, %s, %s )
    ",
        10,
    $metakey,
    $metavalue
) );
Performed in WordPress by add_meta().
<end node> 5P9i0s8y19Z
dt=
<node>plugin
1
[admin plugin]
<?php
./*
Plugin Name: swd_admin
Description: A test plugin to demonstrate wordpress functionality
Author: SWD
Version: 0.1
*/
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu(){
        add_menu_page( 'Test Plugin Page', 'Test Plugin', 'manage_options', 'test-plugin', 'swd_menu' );
}
function swd_menu(){
        echo "<h1>Hello World!</h1>";
}
?>
You may think that it may be super hard, but it really is not.

All you have to do is create a new folder in the plugins directory. Example: /wp-content/plugins/yoursitename-plugin/
Open a blank file and save it as “yoursitename-plugin.php”
Put the following code in the file:
<?php
/*
Plugin Name: Site Plugin for example.com
Description: Site specific code changes for example.com
*/
/* Start Adding Functions Below this Line */

// this is widget code
/* Stop Adding Functions Below this Line */
?>
Now upload this file into the folder you created in the plugins directory. Then simply activate the plugin.
<end node> 5P9i0s8y19Z
dt=
<node>backupWordpress
2
[Resolved] 3.4.3 update getting incorrect root directory
Adding define( 'HMBKP_ROOT', dirname( __FILE__ )); to wp-config.php seems to fix the issue for me, thanks.
<end node> 5P9i0s8y19Z
dt=
<node>Contact form
2
http://www.sitepoint.com/build-your-own-wordpress-contact-form-plugin-in-5-minutes/
short codes
<HEADER>
<H1>Build Your Own WordPress Contact Form Plugin in 5 Minutes</H1>
<DIV>
<FIGURE>
<A href="http://www.sitepoint.com/author/acollins/">
<IMG src="http://1.gravatar.com/avatar/75eb5abf4f342e434c23fb0216631d3e?s=96&d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&r=G">
</A>     </FIGURE>
<DIV>
<DIV>
<A href="http://www.sitepoint.com/author/acollins/">Agbonghama Collins</A>   </DIV>         </DIV>
</DIV>
<DIV>
<P>Published <time>July 23, 2014</time>
</P>
</DIV>
<DIV>
<!– make sure to update trackTweetsAndSubscriptions in scripts.js if the Tweet button DOM path changes in the future –>             <A href="https://twitter.com/share?text=Build+Your+Own+WordPress+Contact+Form+Plugin+in+5+Minutes&via=sitepointdotcom">
<I>
</I>              Tweet             </A>
<!– make sure to update trackTweetsAndSubscriptions in scripts.js if the Subscribe button DOM path changes in the future –>             <A href="https://confirmsubscription.com/h/y/1FD5B523FA48AA2B">
<!–<i>
</i>–>              Subscribe             </A>
</DIV>
</HEADER>
<SECTION>
<P>Most websites are typically designed to comply with standard web practices by including a dedicated page where a contact form is located. This provides visitors with an easy way to reach out to the site owner.</P>
<P>In simple terms, a contact form has a set of questions and fields which are filled in by a visitor. The information is usually automatically sent via email to the site administrator or another nominated email account. It is worth noting that this email address isn’t displayed to visitors, so using a contact form typically reduces email spam from bots that harvest naked email addresses on the Internet. Contact forms play a very important role on a website, where they are used for collecting feedback, enquiries and other data from users.</P>
<P>If your website is powered by WordPress, there are numerous plugins that seamlessly integrate a <STRONG>contact form</STRONG> on your website.</P>
<P>In this article, I will provide a list of some free WordPress contact form plugins. I will also discuss why you should consider rolling your own contact form. Then, I will provide you with a short tutorial showing you how to build your own WordPress contact form plugin.</P>
<H2>WordPress Contact Form Plugins</H2>
<P>Before we get started, we’re going to go over a few of the popular free contact form plugins available in the <A href="https://wordpress.org/plugins/">WordPress Plugin Directory</A>. These are great to use, but even better to learn from when you’re getting started building your own plugins.</P>
<P>Below are some of the most highly rated free contact form plugins for WordPress:</P>
<OL>
<LI>
<P>
<A href="http://wordpress.org/plugins/contact-form-7/">Contact Form 7</A> – This is the second <A href="http://wordpress.org/plugins/browse/popular/">most popular plugin</A> with over 18 million downloads, it could almost be considered as the de facto contact form plugin for a WordPress website. Contact Form 7 can manage multiple contact forms and you can customize the form and the email contents with simple markup. The form features include Ajax-powered submission, CAPTCHA, Akismet spam filtering and lots more.</P>
</LI>
<LI>
<P>
<A href="https://wordpress.org/plugins/contact-form-to-email/">Contact Form to Email</A> – This plugin not only creates contact forms and sends the data to a specified email address it also saves the contact form data into a database, providing printable reports and the option to export the selected data to CSV/Excel file.</P>
</LI>
<LI>
<P>
<A href="http://wordpress.org/plugins/formget-contact-form/">FormGet Contact Form</A> – An easy online drag and drop contact form builder tool. All you need to do is click on the fields that you want in your form, and within few seconds your contact form is ready.</P>
</LI>
<LI>
<P>
<A href="http://wordpress.org/plugins/contact-form-plugin/">Bestwebsoft Contact Form</A> – Allows you to implement a feedback form to a web page or a post effortlessly. It is extremely easy, and you won’t require any additional settings, even though there are some available to play with.</P>
</LI>
</OL>
<H2>Why Roll Your Own Contact Form Plugin?</H2>
<H3>Becoming a Better Developer</H3>
<P>Developing your own WordPress plugin helps you better understand how WordPress works ‘under the hood’ which can help you to become a more experienced web developer. While there are tens of thousands of plugins in the WordPress Plugin Directory to use, being able to modify and extend other plugins is a very useful skill.</P>
<H3>Building a Better Form</H3>
<P>Many WordPress contact form plugins are bloated. They include many features that you may never use. Heavy usage of JavaScript and CSS files are also common in some of the standard contact form plugins. This increases the number of HTTP requests which adversely affects WordPress performance.</P>
<P>According to <A href="http://developer.yahoo.com/performance/rules.html#num_http">Yahoo’s performance rules</A>:</P>
<BLOCKQUOTE>
<P>80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.</P>
</BLOCKQUOTE>
<P>If you are like me, and you desire a simple contact form plugin that just works, read on. I’ll guide you through the simple process of develop your own plugin so you can kiss goodbye bloated plugins. In this example no extra CSS and JavaScript files are required, the <A href="http://www.sitepoint.com/client-side-form-validation-html5/">validation done using HTML5</A>.</P>
<H2>Contact Form Plugin Development</H2>
<P>In five minutes, you will learn how to develop a simple WordPress contact form, that’s a promise!</P>
<P>Ready? Set? Go!</P>
<P>All WordPress pluigns are PHP files, located in the <CODE>/wp-content/plugins/ directory</CODE>. In our example, the file will be called <CODE>sp-form-example.php</CODE>. I assume you’re comfortable with connecting to your server using FTP/SFTP/SCP or SSH.</P>
<P>If you want to follow along, simply create a file called <CODE>sp-form-example.php</CODE> (the final complete example will be available at the end of the article):</P>
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
<DIV>1</DIV>
<DIV>2</DIV>
<DIV>3</DIV>
<DIV>4</DIV>
<DIV>5</DIV>
<DIV>6</DIV>
<DIV>7</DIV>
<DIV>8</DIV>
<DIV>9</DIV>
<DIV>10</DIV>
<DIV>11</DIV>
<DIV>12</DIV>
<DIV>13</DIV>
</TD>
<TD>
<DIV>
<DIV>
<CODE class="php plain"><?php</CODE>
</DIV>
<DIV>
<CODE class="php comments">/*</CODE>
</DIV>
<DIV>
<CODE class="php comments">Plugin Name: Example Contact Form Plugin</CODE>
</DIV>
<DIV>
<CODE class="php comments">Plugin URI: <A href="http://example.com/">http://example.com</A>
</CODE>
</DIV>
<DIV>
<CODE class="php comments">Description: Simple non-bloated WordPress Contact Form</CODE>
</DIV>
<DIV>
<CODE class="php comments">Version: 1.0</CODE>
</DIV>
<DIV>
<CODE class="php comments">Author: Agbonghama Collins</CODE>
</DIV>
<DIV>
<CODE class="php comments">Author URI: <A href="http://w3guy.com/">http://w3guy.com</A>
</CODE>
</DIV>
<DIV>
<CODE class="php comments">*/</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php comments">//</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php comments">// the plugin code will go here..</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php comments">//</CODE>
</DIV>
<DIV>
<CODE class="php plain">?></CODE>
</DIV>
</DIV>
</TD>
</TR>
</TBODY>
</TABLE>
</DIV>
</DIV>
<P>Next, we add the function <CODE>html_form_code()</CODE> that contains the contact form HTML:</P>
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
<DIV>1</DIV>
<DIV>2</DIV>
<DIV>3</DIV>
<DIV>4</DIV>
<DIV>5</DIV>
<DIV>6</DIV>
<DIV>7</DIV>
<DIV>8</DIV>
<DIV>9</DIV>
<DIV>10</DIV>
<DIV>11</DIV>
<DIV>12</DIV>
<DIV>13</DIV>
<DIV>14</DIV>
<DIV>15</DIV>
<DIV>16</DIV>
<DIV>17</DIV>
<DIV>18</DIV>
<DIV>19</DIV>
<DIV>20</DIV>
<DIV>21</DIV>
</TD>
<TD>
<DIV>
<DIV>
<CODE class="php keyword">function</CODE> <CODE class="php plain">html_form_code() {</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<form action="'</CODE> <CODE class="php plain">. esc_url( </CODE>
<CODE class="php variable">$_SERVER</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">'REQUEST_URI'</CODE>
<CODE class="php plain">] ) . </CODE>
<CODE class="php string">'" method="post">'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'Your Name (required) <br />'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="'</CODE> <CODE class="php plain">. ( isset( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">["cf-name</CODE>
<CODE class="php string">"] ) ? esc_attr( $_POST["</CODE>
<CODE class="php plain">cf-name</CODE>
<CODE class="php string">"] ) : '' ) . '"</CODE> <CODE class="php plain">size=</CODE>
<CODE class="php string">"40"</CODE> <CODE class="php plain">/>';</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'</p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'Your Email (required) <br />'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<input type="email" name="cf-email" value="'</CODE> <CODE class="php plain">. ( isset( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">["cf-email</CODE>
<CODE class="php string">"] ) ? esc_attr( $_POST["</CODE>
<CODE class="php plain">cf-email</CODE>
<CODE class="php string">"] ) : '' ) . '"</CODE> <CODE class="php plain">size=</CODE>
<CODE class="php string">"40"</CODE> <CODE class="php plain">/>';</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'</p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'Subject (required) <br />'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="'</CODE> <CODE class="php plain">. ( isset( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">["cf-subject</CODE>
<CODE class="php string">"] ) ? esc_attr( $_POST["</CODE>
<CODE class="php plain">cf-subject</CODE>
<CODE class="php string">"] ) : '' ) . '"</CODE> <CODE class="php plain">size=</CODE>
<CODE class="php string">"40"</CODE> <CODE class="php plain">/>';</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'</p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'Your Message (required) <br />'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<textarea rows="10" cols="35" name="cf-message">'</CODE> <CODE class="php plain">. ( isset( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">"cf-message"</CODE>
<CODE class="php plain">] ) ? esc_attr( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">"cf-message"</CODE>
<CODE class="php plain">] ) : </CODE>
<CODE class="php string">''</CODE> <CODE class="php plain">) . </CODE>
<CODE class="php string">'</textarea>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'</p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<p><input type="submit" name="cf-submitted" value="Send"/></p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'</form>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php plain">}</CODE>
</DIV>
</DIV>
</TD>
</TR>
</TBODY>
</TABLE>
</DIV>
</DIV>
<P>Basic validation was added to the form via the <CODE>pattern</CODE> input attribute.</P>
<P>The RegEX in the contact form does the following field validation:</P>
<UL>
<LI>
<P>
<STRONG>[a-zA-Z0-9 ]</STRONG>: only letters, spaces and numbers allowed in the name field; special symbols are deemed invalid.</P>
</LI>
<LI>
<P>
<STRONG>[a-zA-Z ]</STRONG>: only letters and spaces are allowed in the subject field.</P>
</LI>
<LI>
<P>The <CODE>email</CODE> form control validates the email field hence there is no need for a pattern attribute.</P>
</LI>
</UL>
<P>For more information on how this works, read my article on <A href="http://www.sitepoint.com/client-side-form-validation-html5/">Client-Side Form Validation with HTML5</A> to understand how the pattern attribute assists with form validation.</P>
<H3>Hurry Up!</H3>
<P>Okay, how many minutes do we have left? Four minutes! We still have time to get this over with.</P>
<P>The function <CODE>deliver_mail()</CODE> sanitizes the form data and sends the mail to the WordPress administrator’s email address.</P>
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
<DIV>1</DIV>
<DIV>2</DIV>
<DIV>3</DIV>
<DIV>4</DIV>
<DIV>5</DIV>
<DIV>6</DIV>
<DIV>7</DIV>
<DIV>8</DIV>
<DIV>9</DIV>
<DIV>10</DIV>
<DIV>11</DIV>
<DIV>12</DIV>
<DIV>13</DIV>
<DIV>14</DIV>
<DIV>15</DIV>
<DIV>16</DIV>
<DIV>17</DIV>
<DIV>18</DIV>
<DIV>19</DIV>
<DIV>20</DIV>
<DIV>21</DIV>
<DIV>22</DIV>
<DIV>23</DIV>
<DIV>24</DIV>
<DIV>25</DIV>
<DIV>26</DIV>
</TD>
<TD>
<DIV>
<DIV>
<CODE class="php keyword">function</CODE> <CODE class="php plain">deliver_mail() {</CODE>
</DIV>
<DIV> </DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php comments">// if the submit button is clicked, send the email</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php keyword">if</CODE> <CODE class="php plain">( isset( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">'cf-submitted'</CODE>
<CODE class="php plain">] ) ) {</CODE>
</DIV>
<DIV> </DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php comments">// sanitize form values</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php variable">$name</CODE>    <CODE class="php plain">= sanitize_text_field( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">"cf-name"</CODE>
<CODE class="php plain">] );</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php variable">$email</CODE>   <CODE class="php plain">= sanitize_email( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">"cf-email"</CODE>
<CODE class="php plain">] );</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php variable">$subject</CODE> <CODE class="php plain">= sanitize_text_field( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">"cf-subject"</CODE>
<CODE class="php plain">] );</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php variable">$message</CODE> <CODE class="php plain">= esc_textarea( </CODE>
<CODE class="php variable">$_POST</CODE>
<CODE class="php plain">[</CODE>
<CODE class="php string">"cf-message"</CODE>
<CODE class="php plain">] );</CODE>
</DIV>
<DIV> </DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php comments">// get the blog administrator's email address</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php variable">$to</CODE> <CODE class="php plain">= get_option( </CODE>
<CODE class="php string">'admin_email'</CODE> <CODE class="php plain">);</CODE>
</DIV>
<DIV> </DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php variable">$headers</CODE> <CODE class="php plain">= </CODE>
<CODE class="php string">"From: $name <$email>"</CODE> <CODE class="php plain">. </CODE>
<CODE class="php string">"\r\n"</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV> </DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php comments">// If email has been process for sending, display a success message</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php keyword">if</CODE> <CODE class="php plain">( wp_mail( </CODE>
<CODE class="php variable">$to</CODE>
<CODE class="php plain">, </CODE>
<CODE class="php variable">$subject</CODE>
<CODE class="php plain">, </CODE>
<CODE class="php variable">$message</CODE>
<CODE class="php plain">, </CODE>
<CODE class="php variable">$headers</CODE> <CODE class="php plain">) ) {</CODE>
</DIV>
<DIV>
<CODE class="php spaces">            </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<div>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">            </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'<p>Thanks for contacting me, expect a response soon.</p>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">            </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'</div>'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php plain">} </CODE>
<CODE class="php keyword">else</CODE> <CODE class="php plain">{</CODE>
</DIV>
<DIV>
<CODE class="php spaces">            </CODE>
<CODE class="php functions">echo</CODE> <CODE class="php string">'An unexpected error occurred'</CODE>
<CODE class="php plain">;</CODE>
</DIV>
<DIV>
<CODE class="php spaces">        </CODE>
<CODE class="php plain">}</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php plain">}</CODE>
</DIV>
<DIV>
<CODE class="php plain">}</CODE>
</DIV>
</DIV>
</TD>
</TR>
</TBODY>
</TABLE>
</DIV>
</DIV>
<P>The sanitation of the form data is done by the following WordPress internal functions:</P>
<UL>
<LI>
<P>
<CODE>sanitize_text_field()</CODE>: Sanitize the data from user input.</P>
</LI>
<LI>
<P>
<CODE>sanitize_email()</CODE>: Strips out all characters that are not allowable in an email.</P>
</LI>
<LI>
<P>
<CODE>esc_textarea()</CODE>: Escape the <EM>message</EM> text area values.</P>
</LI>
</UL>
<P>The code <CODE>get_option( 'admin_email' )</CODE> programmatically retrieves the WordPress administrator’s email address from the database where the email will be delivered to.</P>
<P>Don’t want the contact form to send the mail to admin? Simply set the variable <CODE>$to</CODE> to the desired email address.</P>
<P>If the email has successfully been processed without any errors by the function <CODE>wp_mail()</CODE> , the text <EM>Thanks for contacting me, expect a response soon</EM> will be shown, otherwise <EM>An unexpected error occurred</EM> is displayed.</P>
<H3>1 Minute and 30 Seconds Left</H3>
<P>The function <CODE>cf_shortcode()</CODE> is the callback function that is called when the contact form shortcode <CODE>[sitepoint_contact_form]</CODE> is active.</P>
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
<DIV>1</DIV>
<DIV>2</DIV>
<DIV>3</DIV>
<DIV>4</DIV>
<DIV>5</DIV>
<DIV>6</DIV>
<DIV>7</DIV>
</TD>
<TD>
<DIV>
<DIV>
<CODE class="php keyword">function</CODE> <CODE class="php plain">cf_shortcode() {</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php plain">ob_start();</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php plain">deliver_mail();</CODE>
</DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php plain">html_form_code();</CODE>
</DIV>
<DIV> </DIV>
<DIV>
<CODE class="php spaces">    </CODE>
<CODE class="php keyword">return</CODE> <CODE class="php plain">ob_get_clean();</CODE>
</DIV>
<DIV>
<CODE class="php plain">}</CODE>
</DIV>
</DIV>
</TD>
</TR>
</TBODY>
</TABLE>
</DIV>
</DIV>
<P>The above functions calls the <CODE>html_form_code()</CODE> and <CODE>deliver_mail()</CODE> functions to display the contact form HTML form and validate the form data respectively.</P>
<P>Finally, the shortcode <CODE>[sitepoint_contact_form]</CODE> is registered to WordPress. So simply add:</P>
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
<DIV>1</DIV>
</TD>
<TD>
<DIV>
<DIV>
<CODE class="php plain">add_shortcode( </CODE>
<CODE class="php string">'sitepoint_contact_form'</CODE>
<CODE class="php plain">, </CODE>
<CODE class="php string">'cf_shortcode'</CODE> <CODE class="php plain">);</CODE>
</DIV>
</DIV>
</TD>
</TR>
</TBODY>
</TABLE>
</DIV>
</DIV>
<H3>3, 2, 1… Time’s Up!</H3>
<P>Congratulations, we have successfully developed our own WordPress contact form plugin and I have fulfilled my earlier promise.</P>
<P>Now, to use this plugin on your website, simply activate it in under the ‘Plugins’ section of your WordPress dashboard, then create a post or page and then simply add the shortcode where you want the form to appear <CODE>[sitepoint_contact_form]</CODE>.</P>
<P>If you then preview the page and you should see the contact form displayed as shown below.</P>
</SECTION>
<end node> 5P9i0s8y19Z
dt=
<node>shortcodes
2
<?php
/*
* Plugin Name: WordPress ShortCode
* Description: Create your WordPress shortcode.
* Version: 1.0
* Author: InkThemes
* Author URI: https://inkthemes.com
*/
// Example 1 : WP Shortcode to display form on any page or post.
function form_creation(){
$imagedirectory="../stylists/";
$dir = opendir($imagedirectory);
while ($file = readdir($dir)){
//for ($i=1; $i<=500; $i++){
//   $file = readdir($dir);
    $fullpath=$current_dir.$file; $fullpath2=$current_dir."/stylists/large/".$file;
    /*
    $filedate=date('Y-m-j', filemtime($fullpath));
    if(trim($file)!='.' && trim($file)!='..'){
        $fsize=filesize($fullpath)/1000;
        $fsize=(int)$fsize;$fsize=$fsize/1000;
        $message[]=$filedate."|".$file."@".$fsize;
    }
    */
    echo "<div style='float:left;padding:20px;'><a href='$fullpath2'><img src='$fullpath'><br>$file</a></div>";
}
  closedir($dir);
}
add_shortcode('test', 'form_creation');
?>
[test] in whatever page you want
<end node> 5P9i0s8y19Z
dt=
<node>WIDGET
1
<?php
/**
* Plugin Name: A simple Widget
* Description: A widget that displays authors name.
* Version: 0.1
* Author: Bilal Shaheen
* Author URI: http://gearaffiti.com/about
*/
add_action( 'widgets_init', 'my_widget' );
function my_widget() {
    register_widget( 'SWDWidget' );
}
class SWDWidget extends WP_Widget {
    function SWDWidget() {
        $widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays SWD garbage ', 'example') );
        
        $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'swd_widget' );
        
        $this->WP_Widget( 'swd_widget', __('SWD Input', 'example'), $widget_ops, $control_ops );
    }
    
    function widget( $args, $instance ) {
        extract( $args );
        //Our variables from the widget settings.
        $title = apply_filters('widget_title', $instance['title'] );
        $name = $instance['name'];
        $show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false;
        echo $before_widget;
        // Display the widget title
        if ( $title )
            echo $before_title . $title . $after_title;
        //Display the name on website
        if ( $name )
            printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example1') . '</p>', $name );
        
        if ( $show_info )
            printf( $name );
        
        echo $after_widget;
    }
    //Update the widget
    
    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        //Strip tags from title and name to remove HTML
        $instance['title'] = strip_tags( $new_instance['title'] );
        $instance['name'] = strip_tags( $new_instance['name'] );
        $instance['show_info'] = $new_instance['show_info'];
        return $instance;
    }
    
    function form( $instance ) {
        //Set up some default widget settings.
        $defaults = array( 'title' => __('Example44', 'example1'), 'name' => __('Bilal Shaheen', 'example1'), 'show_info' => true );
        $instance = wp_parse_args( (array) $instance, $defaults ); ?>
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'example1'); ?></label>
            <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
        </p>
        //Text Input.
        <p>
            <label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e('Your Name:', 'example1'); ?></label>
            <textarea id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>"><?php echo $instance['name']; ?></textarea>
        </p>
        
        //Checkbox.
        <p>
            <input class="checkbox" type="checkbox" <?php checked( $instance['show_info'], true ); ?> id="<?php echo $this->get_field_id( 'show_info' ); ?>" name="<?php echo $this->get_field_name( 'show_info' ); ?>" />
            <label for="<?php echo $this->get_field_id( 'show_info' ); ?>"><?php _e('Display info publicly?', 'example'); ?></label>
        </p>
    <?php
    }
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>example
2
[code]
Before we get started, it would be best if you create a site-specific plugin where you will be pasting widget code. You can also paste it in your theme’s functions.php file but a site-specific plugin is better.
In this tutorial, we will create a simple widget that just greets visitors. Take a look at this code and then paste it in your site-specific plugin to see it in action.
01 // Creating the widget
02 class wpb_widget extends WP_Widget {
03
04 function __construct() {
05 parent::__construct(
06 // Base ID of your widget
07 'wpb_widget',
08
09 // Widget name will appear in UI
10 __('WPBeginner Widget', 'wpb_widget_domain'),
11
12 // Widget description
13 array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), )
14 );
15 }
16
17 // Creating widget front-end
18 // This is where the action happens
19 public function widget( $args, $instance ) {
20 $title = apply_filters( 'widget_title', $instance['title'] );
21 // before and after widget arguments are defined by themes
22 echo $args['before_widget'];
23 if ( ! empty( $title ) )
24 echo $args['before_title'] . $title . $args['after_title'];
25
26 // This is where you run the code and display the output
27 echo __( 'Hello, World!', 'wpb_widget_domain' );
28 echo $args['after_widget'];
29 }
30
31 // Widget Backend
32 public function form( $instance ) {
33 if ( isset( $instance[ 'title' ] ) ) {
34 $title = $instance[ 'title' ];
35 }
36 else {
37 $title = __( 'New title', 'wpb_widget_domain' );
38 }
39 // Widget admin form
40 ?>
41 <p>
42 <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
43 <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
44 </p>
45 <?php
46 }
47
48 // Updating widget replacing old instances with new
49 public function update( $new_instance, $old_instance ) {
50 $instance = array();
51 $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
52 return $instance;
53 }
54 } // Class wpb_widget ends here
55
56 // Register and load the widget
57 function wpb_load_widget() {
58 register_widget( 'wpb_widget' );
59 }
60 add_action( 'widgets_init', 'wpb_load_widget' );
Now go to Appearance » Widgets, drag and drop WPBeginner Widget in your sidebar to see this custom widget in action.
Simple wasn’t it? First we created a custom widget. Then we defined what that widget does and how to display the widget back-end. Then we defined how to handle changes made to widget. Lastly, we registered and loaded the widget.
Now there are a few things that you might want to ask. For example, what wpb_text_domain does? WordPress uses gettext to handle translation and localization. This wpb_text_domain and __e tells gettext to make a string available for translation. See how you can find translation ready WordPress themes.
We hope this tutorial helped you learn how to create a custom WordPress widget. Let us know what widgets you are creating, by leaving a comment below.
=====================================
// used on the windsor hair shoppe
<?php
/*
Plugin Name: Social Media Icons
Plugin URI: http://softwarewebdesign.com
Description: Adds Icons.
Version: 1.0
Author: Software Web Design
Author URI: http://softwarewebdesign.com
License: GPL2
*/
class WP_Widget_SocialMedia extends WP_Widget {

    // The widget construct. Mumbo-jumbo that loads our code.
    function WP_Widget_SocialMedia() {
        $widget_ops = array( 'classname' => 'widget_SocialMedia', 'description' => __( "Social Media Icons" ) );
        $this->WP_Widget('SocialMedia', __('SocialMedia'), $widget_ops);
    } // End function WP_Widget_SocialMedia

    // This code displays the widget on the screen.
    function widget($args, $instance) {
        extract($args);
        echo $before_widget;
        if(!empty($instance['title'])) {
            echo $before_title . $instance['title'] . $after_title;
        }
        echo "<p><a href='http://www.facebook.com/pages/Windsor-Hair-Shoppe/469480233075402'><img src='".site_url()."/images/facebook.jpg'></a></p>";
        echo $after_widget;
    } // End function widget.

    // Updates the settings.
    function update($new_instance, $old_instance) {
        return $new_instance;
    } // End function update
    // The admin form.
    function form($instance) {        
        echo '<div id="bareBones-admin-panel">';
        echo '<label for="' . $this->get_field_id("title") .'">Social Media Title:</label>';
        echo '<input type="text" class="widefat" ';
        echo 'name="' . $this->get_field_name("title") . '" ';
        echo 'id="' . $this->get_field_id("title") . '" ';
        echo 'value="' . $instance["title"] . '" />';
        echo '<p>This widget will display Social Media Icons below.</p>';
        echo '</div>';
    } // end function form

} // end class WP_Widget_BareBones

// Register the widget.
add_action('widgets_init', create_function('', 'return register_widget("WP_Widget_SocialMedia");'));
?>
==============================================================================
http://www.briangardner.com/welcome-text-widget/
<?php
/*
Plugin Name:  JAD Simple Widget Template
Plugin URI:   http://www.johnathanandersendesign.com/
Description:  A very basic widget structure to hack around with.
Version:      0.1
Author:       Johnathan Andersen Design
Author URI:   http://www.johnathanandersendesign.com/    
*/
    function jad_simple_widget($args, $widget_args = 1) {
    /*
        extract( $args, EXTR_SKIP );
        if ( is_numeric($widget_args) )
            $widget_args = array( 'number' => $widget_args );
        $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
        extract( $widget_args, EXTR_SKIP );
    
        $options = get_option('simple_widget');
        if ( !isset($options[$number]) )
        return;
        $title = $options[$number]['title'];         // single value
        $text = $options[$number]['text'];         // single value
        $check = $options[$number]['check'];         // multi value
        $radio = $options[$number]['radio'];         // single value
        $select = $options[$number]['select'];     // single value
        $textarea = $options[$number]['textarea']; // single value
        echo $before_widget; // start widget display code
        */
?>

    <?php echo "LINE 1"; // end widget display code
    
    }
    
    
    function jad_simple_widget_control($widget_args) {
        global $wp_registered_widgets;
        static $updated = false;
        /*
        if ( is_numeric($widget_args) )
            $widget_args = array( 'number' => $widget_args );
        $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
        extract( $widget_args, EXTR_SKIP );
        $options = get_option('simple_widget');
        if ( !is_array($options) )
            $options = array();
        if ( !$updated && !empty($_POST['sidebar']) ) {
            $sidebar = (string) $_POST['sidebar'];
            $sidebars_widgets = wp_get_sidebars_widgets();
            if ( isset($sidebars_widgets[$sidebar]) )
                $this_sidebar =& $sidebars_widgets[$sidebar];
            else
                $this_sidebar = array();
            foreach ( (array) $this_sidebar as $_widget_id ) {
                if ( 'jad_simple_widget' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number']) ) {
                    $widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
                    if ( !in_array( "simple-widget-$widget_number", $_POST['widget-id'] ) ) // the widget has been removed.
                        unset($options[$widget_number]);
                }
            }
            foreach ( (array) $_POST['simple-widget'] as $widget_number => $simple_widget ) {
                if ( !isset($simple_widget['title']) && isset($options[$widget_number]) ) // user clicked cancel
                    continue;
                $title = strip_tags(stripslashes($simple_widget['title']));
                $text = strip_tags(stripslashes($simple_widget['text_value']));
                $check = $simple_widget['check_array'];
                $radio = $simple_widget['radio_value'];
                $select = $simple_widget['select_value'];
                $textarea = $simple_widget['textarea_value'];
                // Pact the values into an array
                $options[$widget_number] = compact( 'title', 'text', 'check', 'radio', 'select', 'textarea' );
            }
            update_option('simple_widget', $options);
            $updated = true;
        }
        if ( -1 == $number ) { // if it's the first time and there are no existing values
            $title = '';
            $text = '';
            $check = '';
            $radio = '';
            $select = '';
            $textarea = '';
            $number = '%i%';
        } else { // otherwise get the existing values
            $title = attribute_escape($options[$number]['title']);
            $text = attribute_escape($options[$number]['text']); // attribute_escape used for security
            $check = $options[$number]['check'];
            $radio = $options[$number]['radio'];
            $select = $options[$number]['select'];
            $textarea = format_to_edit($options[$number]['textarea']);
        }
        print_r($options[$number]);
    */
     ECHO "lINE2";
    }
    
    
    function jad_simple_widget_register() {
        if ( !$options = get_option('simple_widget') )
            $options = array();
        $widget_ops = array('classname' => 'simple_widget', 'description' => __('Test widget form'));
        $control_ops = array('width' => 400, 'height' => 350, 'id_base' => 'simple-widget');
        $name = __('JAD Simple Widget');
    
        $id = false;
        
        foreach ( (array) array_keys($options) as $o ) {
    
            if ( !isset( $options[$o]['title'] ) )
                continue;
                        
            $id = "simple-widget-$o";
            wp_register_sidebar_widget($id, $name, 'jad_simple_widget', $widget_ops, array( 'number' => $o ));
            wp_register_widget_control($id, $name, 'jad_simple_widget_control', $control_ops, array( 'number' => $o ));
        }
        
        if ( !$id ) {
            wp_register_sidebar_widget( 'simple-widget-1', $name, 'jad_simple_widget', $widget_ops, array( 'number' => -1 ) );
            wp_register_widget_control( 'simple-widget-1', $name, 'jad_simple_widget_control', $control_ops, array( 'number' => -1 ) );
        }
    }
add_action('init', jad_simple_widget_register, 1);
?>
*** FULL EXAMPLE ****
<?php
/*
Plugin Name:  JAD Simple Widget Template
Plugin URI:   http://www.johnathanandersendesign.com/
Description:  A very basic widget structure to hack around with.
Version:      0.1
Author:       Johnathan Andersen Design
Author URI:   http://www.johnathanandersendesign.com/    
*/
    function jad_simple_widget($args, $widget_args = 1) {
        
        extract( $args, EXTR_SKIP );
        if ( is_numeric($widget_args) )
            $widget_args = array( 'number' => $widget_args );
        $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
        extract( $widget_args, EXTR_SKIP );
    
        $options = get_option('simple_widget');
        if ( !isset($options[$number]) )
        return;
        $title = $options[$number]['title'];         // single value
        $text = $options[$number]['text'];         // single value
        $check = $options[$number]['check'];         // multi value
        $radio = $options[$number]['radio'];         // single value
        $select = $options[$number]['select'];     // single value
        $textarea = $options[$number]['textarea']; // single value
            
        echo $before_widget; // start widget display code ?>
        
            <h2><?=$title?></h2>
            <p><?=$text?></p>
            <ul>
            <?php foreach($check as $value){ ?>
                <li><?=$value?></li>
            <?php } ?>
            </ul>
            <p><?=$radio?></p>
            <p><?=$select?></p>
            <p><?=$textarea?></p>
            
    <?php echo $after_widget; // end widget display code
    
    }
    
    
    function jad_simple_widget_control($widget_args) {
    
        global $wp_registered_widgets;
        static $updated = false;
    
        if ( is_numeric($widget_args) )
            $widget_args = array( 'number' => $widget_args );            
        $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
        extract( $widget_args, EXTR_SKIP );
    
        $options = get_option('simple_widget');
        
        if ( !is_array($options) )    
            $options = array();
    
        if ( !$updated && !empty($_POST['sidebar']) ) {
        
            $sidebar = (string) $_POST['sidebar'];    
            $sidebars_widgets = wp_get_sidebars_widgets();
            
            if ( isset($sidebars_widgets[$sidebar]) )
                $this_sidebar =& $sidebars_widgets[$sidebar];
            else
                $this_sidebar = array();
    
            foreach ( (array) $this_sidebar as $_widget_id ) {
                if ( 'jad_simple_widget' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number']) ) {
                    $widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
                    if ( !in_array( "simple-widget-$widget_number", $_POST['widget-id'] ) ) // the widget has been removed.
                        unset($options[$widget_number]);
                }
            }
    
            foreach ( (array) $_POST['simple-widget'] as $widget_number => $simple_widget ) {
                if ( !isset($simple_widget['title']) && isset($options[$widget_number]) ) // user clicked cancel
                    continue;
                
                $title = strip_tags(stripslashes($simple_widget['title']));
                $text = strip_tags(stripslashes($simple_widget['text_value']));                
                $check = $simple_widget['check_array'];
                $radio = $simple_widget['radio_value'];
                $select = $simple_widget['select_value'];
                $textarea = $simple_widget['textarea_value'];
                
                // Pact the values into an array
                $options[$widget_number] = compact( 'title', 'text', 'check', 'radio', 'select', 'textarea' );
            }
    
            update_option('simple_widget', $options);
            $updated = true;
        }
    
        if ( -1 == $number ) { // if it's the first time and there are no existing values
    
            $title = '';
            $text = '';
            $check = '';
            $radio = '';
            $select = '';
            $textarea = '';
            $number = '%i%';
            
        } else { // otherwise get the existing values
        
            $title = attribute_escape($options[$number]['title']);
            $text = attribute_escape($options[$number]['text']); // attribute_escape used for security
            $check = $options[$number]['check'];
            $radio = $options[$number]['radio'];
            $select = $options[$number]['select'];
            $textarea = format_to_edit($options[$number]['textarea']);
        }
        
        print_r($options[$number]);
    ?>
    <p><label>Widget Title</label><br /><input id="title_value_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][title]" type="text" value="<?=$title?>" /></p>
    <p><label>Text Field</label><br /><input id="text_value_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][text_value]" type="text" size="30" value="<?=$text?>" /></p>
    <p>
        <label>Checkbox Group</label><br />
        Value 1 <input id="check_array_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][check_array][1]" type="checkbox" <?php if($check[1]){ echo 'checked="checked"';} ?> value="One" /><br />
        Value 2 <input id="check_array_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][check_array][2]" type="checkbox" <?php if($check[2]){ echo 'checked="checked"';} ?> value="Two" /><br />
        Value 3 <input id="check_array_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][check_array][3]" type="checkbox" <?php if($check[3]){ echo 'checked="checked"';} ?> value="Three" /><br />
        Value 4 <input id="check_array_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][check_array][4]" type="checkbox" <?php if($check[4]){ echo 'checked="checked"';} ?> value="Four" />
    </p>
    <p>
        <label>Radio Field</label><br />
        Yes <input id="radio_value_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][radio_value]" type="radio" <?php if($radio == 'yes') echo 'checked="checked"'; ?> value="yes" />
        No <input id="radio_value_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][radio_value]" type="radio" <?php if($radio == 'no') echo 'checked="checked"'; ?> value="no" />
    </p>
    <p>
        <label>Select Menu
        <select id="select_value_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][select_value]">
            <option <?php if ($select == 'One') echo 'selected'; ?> value="One">Value 1</option>
            <option <?php if ($select == 'Two') echo 'selected'; ?> value="Two">Value 2</option>
            <option <?php if ($select == 'Three') echo 'selected'; ?> value="Three">Value 3</option>
            <option <?php if ($select == 'Four') echo 'selected'; ?> value="Four">Value 4</option>
        </select>
        </label>
    </p>
    <p><label>Textarea</label><br /><textarea id="textarea_value_<?php echo $number; ?>" name="simple-widget[<?php echo $number; ?>][textarea_value]" type="text" cols="30" rows="4"><?=$textarea?></textarea></p>
    <input type="hidden" name="simple-widget[<?php echo $number; ?>][submit]" value="1" />
    
    <?php
    }
    
    
    function jad_simple_widget_register() {
        if ( !$options = get_option('simple_widget') )
            $options = array();
        $widget_ops = array('classname' => 'simple_widget', 'description' => __('Test widget form'));
        $control_ops = array('width' => 400, 'height' => 350, 'id_base' => 'simple-widget');
        $name = __('JAD Simple Widget');
    
        $id = false;
        
        foreach ( (array) array_keys($options) as $o ) {
    
            if ( !isset( $options[$o]['title'] ) )
                continue;
                        
            $id = "simple-widget-$o";
            wp_register_sidebar_widget($id, $name, 'jad_simple_widget', $widget_ops, array( 'number' => $o ));
            wp_register_widget_control($id, $name, 'jad_simple_widget_control', $control_ops, array( 'number' => $o ));
        }
        
        if ( !$id ) {
            wp_register_sidebar_widget( 'simple-widget-1', $name, 'jad_simple_widget', $widget_ops, array( 'number' => -1 ) );
            wp_register_widget_control( 'simple-widget-1', $name, 'jad_simple_widget_control', $control_ops, array( 'number' => -1 ) );
        }
    }
add_action('init', jad_simple_widget_register, 1);
?>
<end node> 5P9i0s8y19Z
dt=
<node>new area
2
http://howtomatter.com/how-to-create-a-new-widget-area/
I’ve found it helpful in certain situations to have widgetized areas (that is, places I can drag/drop widgets into from the Appearance>Widget menu) other than the standard Sidebar 1 and Sidebar 2. Certain themes have this built in, but it’s not terribly difficult to create them yourself, so I thought I’d write up a quick tutorial.
What is a new widget area?
As always, head on over to my test site to see an example of what I’m talking about. Scroll down to the footer and you’ll see a light red area with 2 boxes in it that say something along the lines of ‘this is your new sidebar’. In case that site/example is gone by the time you’re reading this, here’s a picture of it.
New Sidebar for Widgets
click to enlarge
So what I’ve done is created 2 new sidebar areas and placed them, in this case, after the content box. Widgets can be dragged into these sidebars in the same way as you’d add widgets to the default sidebars – by going to the Appearance>Widgets menu and dragging them into the appropriate place. More about that in a minute.
How to create a new widget area
Per my typical approach, I’m just going to give you the code, and the instructions on where/how to place it, and if you have questions beyond this or want to know more about how/why it works, you can leave a comment or reach out to me individually…cool?
Okay, so the first thing we need to do is register the new sidebars. This is done by going to the Thesis>Custom File Editor menu, and from the drop down menu at the top of that page, choose ‘custom_functions.php’ and click the ‘edit selected file’ button to its right. Once there, scroll down to the very bottom and paste the following code:
/****************************************************************
   * REGISTER NEW SIDEBARS
****************************************************************/
$args = array(
    'name'          => 'New Sidebar %d',
    'before_widget' => '<li id="%1$s" class="widget %2$s">',
    'after_widget'  => '</li>',
    'before_title'  => '<h3>',
    'after_title'   => '</h3>' );
register_sidebars( 2, $args );
/****************************************************************
   * CREATES NEW SIDEBARS
****************************************************************/
function new_sidebars(){
    ?>
    <div id="new-sidebars">
        <div id="new-sidebar-1">
            <ul class="sidebar_list">
                <?php if (!dynamic_sidebar('New Sidebar 1') ) { ?>
                    <li class="widget">
                        <div class="widget_box">
                            <h3><?php _e('New Sidebar 1', 'thesis'); ?></h3>
                            <p>This is your new sidebar.  Add widgets here from your WP Dashboard just like normal.</p>
                        </div>
                    </li>
                <?php  }   ?>
             </ul>
        </div>
        <div id="new-sidebar-2">
            <ul class="sidebar_list">
                <?php if (!dynamic_sidebar('New Sidebar 2') ) { ?>
                    <li class="widget">
                        <div class="widget_box">
                            <h3><?php _e('New Sidebar 2', 'thesis'); ?></h3>
                            <p>This is your new sidebar.  Add widgets here from your WP Dashboard just like normal.</p>
                        </div>
                    </li>
                <?php  }   ?>
             </ul>
        </div>
    </div>
    <?php
}
add_action('thesis_hook_after_content_box', 'new_sidebars');
So what that has done is created 2 new sidebars and placed them at the bottom of your content box…well, after it, actually. If you were to look at your site now, you’d see them placed one on top of the other…not what we want in this case, but we’ll remedy that with a little CSS styling.
Styling your newly created sidebars
Now that these widgetized sidebars are created, we need to style them to look how we want them to look. So, go to the Thesis>Custom File Editor menu, and make sure it says ‘custom.css’ in the drop down menu. Scroll down to the bottom (or to the appropriate place if you’ve got this file organized) and paste the following code:
/***********************************
NEW WIDGET STYLING
***********************************/
#new-sidebars {
    float:left;
    width:100%;
    background-color:#ffaaaa;
    border-bottom:.1em solid #000000;
}
#new-sidebar-1 {
    float:left;
    margin-left:7em;
    width:40%;
}
#new-sidebar-2 {
    float:left;
    margin-left:2em;
    width:40%;
}
If everything was done properly, you should now have two sidebars after your content box that look very similar to/the same as what’s pictured above.
Add widgets to your new sidebarsAnd if you go to your Appearance>Widgets menu, you should now see 2 new boxes in the right column where you can drag widgets. Just click the drop down arrow to expand them (pictured here) and you can begin dragging widgets into them…text, pictures, recent post widgets, whatever you like.
What if I want my widgetized sidebars to appear somewhere else?
Okay, so what if you don’t want these new widget areas to appear below your content box? No problem, you just need to ‘hook’ them to the area you do want them in. Look at the 1st bit of code above (that went into your custom_functions.php file). The last line says “add action…”, and you see ‘thesis_hook_after_content_box’. That ‘after_content_box is the hook we used and it tells Thesis to place it in that specific area.
Well, Thesis has lots of hooks available (a hook essentially just refers to a different place on your site you can ‘hang’ code). Check out this visual reference and click on one of the thumbnail images you see there. As you’ll see, the hooks are all over the place and they each refer to a different spot on the page. Choose where you want your widgetized sidebars to go and replace ‘after_content_box’ in the above code with the hook you want.
Of course, that will require you to style your sidebars differently because the size of the space/hook you’re placing them in/on will determine how you style them. If you decide to do that, leave me a comment and I’ll show you how to do it.
Things to keep in mind
    We registered/created just 2 widgetized sidebars. If you want more, that’s totally doable and it’s a matter of a few tweaks to the above code. Comment me if you would like to learn how to do so.
    Depending on what widget(s) you drop into these newly created sidebars, your styling (CSS) may need to be altered (an image, for example, may be taller than, say, a list of links, etc), so if you run into an issue where it just doesn’t look right, comment me.
Alright, so that wraps things up. If anything is unclear or doesn’t work or if you need some additional support, please holler. And of course, if you’re at your wit’s end and want to hire me to build you a WordPress site or provide some WordPress Coaching, please do.
Cheers…
=========================================================
http://www.studiograsshopper.ch/code-snippets/how-to-add-a-widgetised-area-in-a-wordpress-theme/
How to add a Widgetised area in a WordPress theme
July 11, 2009 26 Comments
Darling, I'm not in the mood to go dancing. Let's stay home and code widgets instead!
Darling, I'm not in the mood to go dancing. Let's stay home and code widgets instead!
Here’s a tutorial to show you how to add a widget to a theme template file.
Most themes these days come with built-in widget support, most commonly in the sidebar, but also sometimes in other parts of the theme such as the header, homepage or single post pages.
In this tutorial I show you how to add a widget area to single post pages, and how to use the new widget area to display an advert on every single post page.
Widget basics
There are only four things we need to know in order to set up our new widget area:
    Which theme template file we need to edit
    The code for a Widget area, which we will place in the relevant theme template file
    How to “register” a Widget area, usually in the theme’s functions.php, in order to tell WordPress that the widget area exists and therefore allow you to add widgets to this widget area in the Dashboard.
    Add some styling to the widget area so that it fits in with the look of our site.
Which template file?
If you familiar with WordPress you will know that different pages on your site are produced by different theme template files. Which template file is used to display different views of your site is taken care of by WordPress, behind the scenes, and follows the Template Hierarchy coded into the WordPress Core files.
In our example, we want to add the widget area to the single post page. Depending on your theme this will be either single.php or index.php. In our example, let’s assume it is index.php.
Adding Widget code to the theme file
Open up your index.php (take a backup first, just in case you need to put everything back to how it was) and decide where you want the new widget area to appear. Typically, your index.php file will be structured something like this (I’ve left out most of the code to keep things simple):
1    <?php get_header(); ?>
2    
3    <div id="content">
4    
5        <div id="contentleft">
6        
7            <div class="postarea">
8            
9            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
10                
11                // Loop stuff goes here eg Title, Date, Content etc
12                
13                                    
14                <!–
15                <?php trackback_rdf(); ?>
16                –>
17                
18                <?php endwhile; else: ?>
19                
20                <p><?php _e('Sorry, no posts matched your criteria.'); ?></p><?php endif; ?>
21                
22            </div><!– End of postarea –>
23                
24            <div class="postcomments">
25                
26                <?php comments_template('',true); ?>
27            
28            </div>
29            
30        </div>
31        
32        <?php include(TEMPLATEPATH."/sidebar.php");?>
33                
34    </div>
35    
36    <?php get_footer(); ?>
Your index.php file may not have the same DIV id name’s, but the structure should be similar: a DIV containing the Loop, in this case the postarea div (lines 7-22), and a DIV containing the call to the comments template, in this case the postcomments DIV (lines 24-28).
We want to place our widget area between these two DIVs. That way, the widget content will display below the post content and above the comments section of the page.
First, let’s add a new DIV and give it a new class called “widget-post”. You can name this class whatever you like, but choose something that has some meaning so that it’s easier to remember its purpose. Here’s our added code in lines 24-28:
1    </div><!– End of postarea –>
2    
3    <div class="widget-post">
4    
5        // Our widget stuff will go here…
6    
7    </div>
8                
9    <div class="postcomments">
10                
11        <?php comments_template('',true); ?>
12            
13    </div>
Now let’s add the code to display our new widget area. Here it is:
1    </div><!– End of postarea –>
2    
3    <div class="widget-post">
4    
5        <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Post Widget') ) : ?>
6        <?php endif; ?>
7    
8    </div>
9                
10    <div class="postcomments">
11                
12        <?php comments_template('',true); ?>
13            
14    </div>
The new code we’ve added will pull in the widget content. In plain English, the code says – if widgets aren’t enabled in this theme or a widget area called “Post Widget” hasn’t been registered, do nothing. Therefore, if widgets are enabled and the widget area called “Post Widget” exists, the widget content will be displayed here. That’s it – no more work needed on the template file, and it’s time to add the “register” code in functions.php.
Registering the widget in functions.php
We now need to tell WordPress that it should enable a widget area called “Post Widget”. Open up your functions.php and look for a block of code something like this:
1    if ( function_exists('register_sidebars') ) {
2        register_sidebar(array('name'=>'Sidebar 1',));
3        register_sidebar(array('name'=>'Sidebar 2',));
4        register_sidebar(array('name'=>'Sidebar 3',));
5    }
This is the section of code that tells WordPress to enable widget areas. All we need to do is add a new line to this block of code to register our new widget area. Like this:
1    if ( function_exists('register_sidebars') ) {
2        register_sidebar(array('name'=>'Sidebar 1',));
3        register_sidebar(array('name'=>'Sidebar 2',));
4        register_sidebar(array('name'=>'Sidebar 3',));
5        register_sidebar(array('name'=>'Post Widget',));
6    }
The important points to note are:
    We’ve added the extra line below the existing lines, but before the closing curly bracket. This ensures that our changes do not mess up the widgets you’ve already set up in your sidebar, for example.
    We’ve used exactly the same name “Post Widget” that we used in the new code added in index.php above.
Another important point to remember is that the names of widget areas must be unique!
Adding widgets to the new widget area
Go to Dashboard>Appearance>Widgets and you should now see that your Post Widget appears in the righthand side of this screen. You can now drag a Text Widget to the Post Widget, and then add the code necessary to display your adverts within the Text Widget. For example, you can add Google Adsense code here, or affiliate code for a banner ad etc.
View your site and check that on single post pages you now see your adverts between the post content and the comments. If it doesn’t appear, re-check the above steps in case you’ve missed something. If using a newly set up Google Adsense, remember that it can take a short while for the Adsense to populate.
Styling the new widget area
You will probably need to adjust your CSS to get the new widget area to fit in with the look of your site. The most important thing to do first is to add something like this to your style.css to define a style for the new widget-post DIV class which is the container for the widget area:
1    .widget-post {
2        background: #FFFFFF;
3        margin: 0px;
4        padding: 10px;
5        width: 600px;
6        }
This is just a starting point – adjust the width, background, padding and margin to suit you.
If you are using Google Adsense, your Google code will already include various styles based on the selections you made when setting up the Google Adsense. If you are posting your own HTML in the Text Widget you will probably have to add some styling to style.css to make the neceesary adjustments. If you are unfamiliar with CSS, check out the many great tutorials that are out there.
And finally…
As you can see, it isn’t too difficult to add a widget area to a theme file. This same method can be used elsewhere in your site to create other widget areas – just remember to name each one uniquely, and have fun
=================================================
How to add widget area http://www.templatemonster.com/help/how-to-add-widget-area.html
    Author: Chris Diaz
    Posted on: April 7, 2011
    Relation: Layout
    Complexity: Advanced
    Tags: widget, WordPress
Rating: 3.3/5 (2 votes cast)

How to add widget area in WordPress
This tutorial will show you how to create new widget area in WordPress. Any widget in WordPress template could be displayed in any place on the page. This could be done using WordPress widget areas.

To add widget area access to your WordPress installation folder.
1. Open ‘wp-content/themes/theme###’ folder.
2. View the functions.php file
3. Use search tool (CTRL+F) and search for ‘widget’. You can fund the following lines:
Here you can see that widgets are defined in the sidebar-init.php file
?
1
2
    
//Widget and Sidebar
require_once $includes_path . 'sidebar-init.php';
This line defines the $includes_path variable value.
?
1
    
$includes_path = TEMPLATEPATH . '/includes/';
These lines shows you that the widgets are defined in the wp-content/themes/theme###/includes/sidebar-init.php file
4. Open sidebar-init.php file. All widget areas are defined here. The following code is used to define wach area:
?
1
2
3
4
5
6
7
8
9
    
    register_sidebar(array(
        'name'          => 'Sidebar 2',
        'id'            => 'sidebar-2',
        'description'   => __( 'Located at the right side of pages.'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
));
To register new widget area copy the code above and paste it before the closing ‘}’ bracket
Change the ‘name’, ‘id’ and ‘description’ values.

5. Now you can insert the widget area to any part of the template. Go back to the ‘wp-content/themes/theme###‘ folder. You can insert the area to any layout file:
    header.php
    footer.php
    single.php
    category.php
    index.php
    sidebar.php etc
6. Paste the following code to the required place to insert the widget area.
?
1
    
<?php if ( ! dynamic_sidebar( 'New Widget Area' ) ) :?><?php endif;?>
Replace ‘New Widget Area’ with your widget area name.
7. If everything has been done correctly the new widget area would be available from the WordPress admin panel Appearance>Widgets (right column) .

Feel free to check the detailed video tutorial below:
<end node> 5P9i0s8y19Z
dt=
<node>saved info
2
?><div id="topbar" class="sidebar widget-area">
<?php
    genesis_structural_wrap( 'topbar' );
    do_action( 'genesis_before_sidebar_widget_area' );
    do_action( 'genesis_sidebar' );
    do_action( 'genesis_after_sidebar_widget_area' );
    genesis_structural_wrap( 'topbar', 'close' );
?>
</div>
<!– begin #featured-top –>
<div id="featured-top">
            <?php if (!dynamic_sidebar('Homepage Top')) : ?>
                <div class="widget">
                    
                    <div class="wrap">
                        <p><?php _e("This is a widgeted area which is called Homepage.", 'genesis'); ?></p>
                    </div><!– end .wrap –>
                </div><!– end .widget –>
            <?php endif; ?>
        </div><!– end #featured-top –>
<end node> 5P9i0s8y19Z
dt=
<node>simple one
2
<?php
/*
Plugin Name: My Widget
Plugin URI: http://mydomain.com
Description: My first widget
Author: Me
Version: 1.0
Author URI: http://mydomain.com
*/
// Block direct requests
if ( !defined('ABSPATH') )
    die('-1');
    
    
add_action( 'widgets_init', function(){
     register_widget( 'My_Widget' );
});    
/**
* Adds My_Widget widget.
*/
class My_Widget extends WP_Widget {
    /**
     * Register widget with WordPress.
     */
    function __construct() {
        parent::__construct(
            'My_Widget', // Base ID
            __('My Widget', 'text_domain'), // Name
            array( 'description' => __( 'My first widget!', 'text_domain' ), ) // Args
        );
    }
    /**
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
    
         echo $args['before_widget'];
        if ( ! empty( $instance['title'] ) ) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
        }
        echo __( 'Hello, World!', 'text_domain' );
        echo $args['after_widget'];
    }
    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        if ( isset( $instance[ 'title' ] ) ) {
            $title = $instance[ 'title' ];
        }
        else {
            $title = __( 'New title', 'text_domain' );
        }
        ?>
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
        </p>
        <?php
    }
    /**
     * Sanitize widget form values as they are saved.
     *
     * @see WP_Widget::update()
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
        return $instance;
    }
} // class My_Widget
<end node> 5P9i0s8y19Z