We can insert post in wordpress using wp_insert_post which is explained Here

In this sample I have created one sample shortcode for displaying plugin on front and in short code function I have added form to display and before that if post is submitted we will insert the post into database.

Almost svery wordpress plugin developer needs to make Admin side listing for any custom table. This table generally store information that is gather from website and/or end users. Listing of table help to view the data in list format. It also allow admin to add, edit and Delete the data. It also allow bulk action for delete.

During my plugin development, I always wonder that how to make admin side listing for custom table which looks same as post and page listing. Also how can I make pagination for the table. I have searched for pagination and found many class to use that you can also found in my previous post. But I want to make it looks like as below:

After Searching for this I come to know that wordpress also providing the class for listing and paging for custom table. Class Name is Wp_List_Table. Wp_List_Table class is used to create admin screens for the wordpress. We need to extends this class and overload its method to use it.

Now the question is how to use this class and create admin side listing for our created custom table.

WordPress is providing one very good example plugin to see how we can create admin side listing for the custom table. You can find the example plugin Here

This example display code using Array of data. Instead of data we can use any database table. For creating your own table listing copy paste data into your file and follow below steps

Step 1: Create a new file under your plugin directory

Step 2: Include WP_List_Table class file into your file as follow:

PHP

1

2

3

if(!class_exists('WP_List_Table')){

require_once(ABSPATH.'wp-admin/includes/class-wp-list-table.php');

}

Step 3: Create class for your custom table and extends it to WP_List_Table.

For this you can copy whole class from example plugin and paste it in your plugin file and rename the class name from TT_Example_List_Table to something else which is preferable for your plugin.

Step 4: If you are using database table for fetching data which will always a case in real life, then delete the example data array.

We will fetch the data from database when it will be needed. Remove the below code:

This method is called when the parent class can’t find a method specifically build for a given column. Generally, it’s recommended to include one method for each column you want to render, keeping your package class neat and organized. For example, if the class needs to process a column named ‘title’, it would first see if a method named $this->column_title() exists – if it does, that method will be used. If it doesn’t, this one will be used. Generally, you should try to use custom column methods as much as possible.

Step 7: If you have any column column which need to be display diffidently from other in the view. We can create this by below syntax

/*$2%s*/$item['ID']//The value of the checkbox should be the record's id

);

}

step 9: get all column. here we specify which column to get for display.

This method dictates the table’s columns and titles. This should return an array where the key is the column slug (and class) and the value is the column’s title text. If you need a checkbox for bulk actions, refer to the $columns array below.

PHP

1

2

3

4

5

6

7

8

9

functionget_columns(){

$columns=array(

'cb'=>'<input type="checkbox" />',//Render a checkbox instead of text

'title'=>'Title',

'rating'=>'Rating',

'director'=>'Director'

);

return$columns;

}

Step 10: Decide which column to make sortable. This Method is optional.

If you want one or more columns to be sortable (ASC/DESC toggle), you will need to register it here. This should return an array where the key is the column that needs to be sortable, and the value is db column to sort by. Often, the key and value will be the same, but this is not always the case (as the value is a column name from the database, not the list table).
This method merely defines which columns should be sortable and makes them clickable – it does not handle the actual sorting. You still need to detect the ORDERBY and ORDER query string variables within prepare_items() and sort your data accordingly (usually by modifying your query).

PHP

1

2

3

4

5

6

7

8

functionget_sortable_columns(){

$sortable_columns=array(

'title'=>array('title',true),//true means its already sorted

'rating'=>array('rating',false),

'director'=>array('director',false)

);

return$sortable_columns;

}

Step 11: Set up bulk action for selected check boxes. This method is optional

If you need to include bulk actions in your list table, this is the place to define them. Bulk actions are an associative array in the format ‘slug’=>’Visible Title’

If this method returns an empty value, no bulk action will be rendered. If you specify any bulk actions, the bulk actions box will be rendered with the table automatically on display().

Also note that list tables are not automatically wrapped in <form> elements, so you will need to create those manually in order for bulk actions to function.

PHP

1

2

3

4

5

6

functionget_bulk_actions(){

$actions=array(

'delete'=>'Delete'

);

return$actions;

}

Now we also need to set up what to do when any one of the bulk action has been called. This can done using below method. This method is optional.

PHP

1

2

3

4

5

6

functionprocess_bulk_action(){

//Detect when a bulk action is being triggered...

if('delete'===$this->current_action()){

wp_die('Items deleted (or they would be if we had items to delete)!');

}

}

step 12: This is most important step for the listing the table and fetching the database values.

Here find and delete the code

PHP

1

$data=$this->example_data;

Below that there is function

PHP

1

2

3

4

5

6

7

functionusort_reorder($a,$b){

$orderby=(!empty($_REQUEST['orderby']))?$_REQUEST['orderby']:'title';//If no sort, default to title

$order=(!empty($_REQUEST['order']))?$_REQUEST['order']:'asc';//If no order, default to asc

$result=strcmp($a[$orderby],$b[$orderby]);//Determine sort order

return($order==='asc')?$result:-$result;//Send final sort direction to usort

}

usort($data,'usort_reorder');

Also delete this code this code is now no more needed as we are sorting through database query. Add The below Code here

PHP

1

2

3

4

5

global$wpdb;

$orderby=(!empty($_REQUEST['orderby']))?$_REQUEST['orderby']:'sent_time';//If no sort, default to title

$order=(!empty($_REQUEST['order']))?$_REQUEST['order']:'asc';//If no order, default to asc

$query='select * from <Table_name> order by '.$orderby.' '.$order;

$data=$wpdb->get_results($query,'ARRAY_A');

Here first we have called global variable which is available in wordpress for the database operation. ‘$wpdb’ . Then set order by and order values and get the data.

Every things else remain as it is in this function no need to change.

step 13: Now we need to create function which will be called when page is going to display. We just need to create object of our newly created class.

<!--Forplugins,we also need toensure that the form posts back toour current page-->

<input type="hidden"name="page"value="<?phpecho$_REQUEST['page']?>"/>

<!--Nowwecanrenderthecompletedlisttable-->

<?php$testListTable->display()?>

</form>

Conclusion

This will create both listing and pagination for custom table in wordpress. I think this is really easy to use it rather creating table by self and searching for the pagination class and adding them to the code.

This helps developers to create very neat and clean code. Also, This code is fully compatible with wordpress.

Please comment your queries, Suggestion, Like or Dislike post here.

Enjoy..!!!

Note: This example which I have used which is already available in wordpress listing table plugin. I have explained using database connection which was missing in the plugin. Hope this will helps every wordpress developers.

Often in many application, such as in WordPress Plugin, we will need to deal with list of records. As the records grow, more records will need to be displayed. There is a catch though, if you retrieve all the records at one go because it will slow the system down.

In order to have a better user experience for record listing, paging comes into play. It’ll not only help to organize the records by limiting the number of records you want to show per page, it also cuts the down the time of retrieving records. Therefore, pagination plays a very important part in providing a great user experience when interacting with the data.

Imaging if you have a list of 1000 or more records that you want to display. Without pagination, listing all the records will definitely take quite awhile and also increase the load for the database server when executing the query. This is not very efficient, even though retrieving records from database can be cheap.

Now let’s say we want to add in pagination into the 1000 records, by specifying the limit, it will only shows the exact amount of records you want to view. This is a huge benefit for the database server load, because we are not retrieving all the records at once.

Below examples are 2 different type of pagination and a demo on how to add pagination into WordPress Plugin.

Simple PHP Pagination Class

Copy the following code and save as pager.php, this file will be the pagination class. With this pagination classfrom Happycodings, it’d help us add pagination to the list of records easily.

/* Find the number of rows returned from a query; Note: Do NOT use a LIMIT clause in this query */

$count=mysql_num_rows(mysql_query("SELECT field FROM table"));

/* Find the number of pages based on $count and $limit */

$pages=$p->findPages($count,$limit);

/* Now we use the LIMIT clause to grab a range of rows */

$result=mysql_query("SELECT * FROM table LIMIT ".$start.", ".$limit);

/* Now get the page list and echo it */

$pagelist=$p->pageList($_GET['page'],$pages);

echo$pagelist;

/* Or you can use a simple "Previous | Next" listing if you don't want the numeric page listing */

//$next_prev = $p->nextPrev($_GET['page'], $pages);

//echo $next_prev;

/* From here you can do whatever you want with the data from the $result link. */

Digg Style Pagination

As the above simple pagination class is enough for us to display a list of page numbering for the records, but what will happen if there are a few hundreds of pages, isn’t the row of page numbering going to be very long too?

Here is another nice Digg Style Pagination class that you can consider if you think there will be a lot of pages for your records.

Go through the guide to customize the style or desired output for the paging you want. Now, to give you a clearer view on how to add this Digg Style Pagination class. Check out below to find out how to add the Digg Style Pagination to a WordPress Plugin.

How To Add Pagination To WordPress Plugin?

If you are building a WordPress plugin that require to display a list of records from database. As records get huge, you will need to have pagination so that you can organize your records well.

First, you will need to download the pagination.class.php and save it in your WordPress Plugin folder.

Next, in the PHP file that you want to list your records, insert the following code. Below are some of the methods we used from the pagination class. For the full list of methods, please refer to Digg Style Pagination Class Help Page.

Note that you will need to change the SQL query, pagination class configuration and table fields, in order to work nicely with your WordPress Plugin.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

<?php

$items=mysql_num_rows(mysql_query("SELECT * FROM wp_table;"));// number of total rows in the database

if($items>0){

$p=newpagination;

$p->items($items);

$p->limit(30);// Limit entries per page

$p->target("admin.php?page=list_record");

$p->currentPage($_GET[$p->paging]);// Gets and validates the current page

$p->calculate();// Calculates what to show

$p->parameterName('paging');

$p->adjacents(1);//No. of page away from the current page

if(!isset($_GET['paging'])){

$p->page=1;

}else{

$p->page=$_GET['paging'];

}

//Query for limit paging

$limit="LIMIT ".($p->page-1)*$p->limit.", ".$p->limit;

}else{

echo"No Record Found";

}

?>

<!--Now we'll display the list of records -->

<div class="wrap">

<h2>List of Records</h2>

<div class="tablenav">

<div class='tablenav-pages'>

<?phpecho$p->show();// Echo out the list of paging. ?>

</div>

</div>

<table class="widefat">

<thead>

<tr>

<th>ID</th>

<th>FullName</th>

<th>Email</th>

</tr>

</thead>

<tbody>

<?php

$sql="SELECT * FROM $wp_table ORDER BY id DESC $limit";

$result=mysql_query($sql)ordie('Error, query failed');

if(mysql_num_rows($result)>0){

while($row=mysql_fetch_assoc($result)){

$id=$row['id'];

$fullname=$row['fullname'];

$email=$row['email'];

?>

<tr>

<td><?phpecho$id;?></td>

<td><?phpecho$fullname;?></td>

<td><?phpecho$email;?></td>

</tr>

<?php

}

}else{?>

<tr>

<td>NoRecordFound!</td>

<tr>

<?php}?>

</tbody>

</table>

</div>

Now you know How to Add a Digg Style Pagination to a WordPress Plugin, it should make your listing of data much more efficient. Pagination saves your time and bandwidth so you can concentrate more on other implementing issues.

Still not sure about this tutorial on adding pagination? Or simply have an idea to share? Feel free to contact us or leave a comment here!

attachment_fields_to_edit

$form_fields is a special array which will be described in detail in a moment.

$post is the attachment as an object (attachments are treated as post objects in WordPress).

attachment_fields_to_save

PHP

1

2

3

4

5

functionmedia_upload_form_handler(){

//Some Code

$post=apply_filters("attachment_fields_to_save",$post,$attachment);

//Some Code

}

$post is the attachment as an array (attachments are treated as post objects in WordPress).

$attachment is the attachment part of the form $_POST which will include the fields setup through the attachment_fields_to_edit hook.

Note:Be careful in your code, as $post is sent to one function as an object and to the other as an array.

We will add this fields information to Custom Fields.

How to add this Fields to Custom Fields for Working is Properly

The new fields being added will be saved as post meta, just like the custom fields section of the post/page edit screen. Fields prefixed with an underscore (_my_custom_field) will not be listed in the drop down of available custom fields on the post/page screen; all other existing post meta fields will be listed. We can use this knowledge to hide the fields we’re adding to the media form, since they aren’t relevant for posts/pages.

There is a similar rule to keep in mind when choosing the $form_fields array key to use for your new field. Here, if you use an underscore ($form_fields[‘_my_custom_field’]) your field will be skipped and will not be added to the form.

So in order to show our fields in the media form, but also not list them in the page/post custom fields drop down, we must combine both methods. This will invlove both the edit and save functions we’ll be creating. For the ‘attachment_fields_to_edit‘ hook we’ll set the $form_fields keys up to not have underscore prefixes, and for the ‘attachment_fields_to_save‘ hook we’ll prefix our fields with an underscore before saving them as post meta. This is a workaround worth doing in order to not muddy our users’ interface with unneeded info.

Hook 1: attachment_fields_to_edit

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<?php

/**

* Adding our custom fields to the $form_fields array

*

* @param array $form_fields

* @param object $post

* @return array

*/

functionmy_image_attachment_fields_to_edit($form_fields,$post){

// $form_fields is a special array of fields to include in the attachment form

The $form_fields array has several options for including different types of inputs and custom content. I’ve compiled the various methods below with notes and screenshots of how they render in the form.

Text Input

PHP

1

2

3

4

// input type="text"

$form_fields["custom1"]["label"]=__("Custom Text Field");

$form_fields["custom1"]["input"]="text";// this is default if "input" is omitted

Hook 2: attachment_fields_to_save

Saving your custom fields is a much simpler process than adding them to the form; just check if your field is set and update its value as post meta. Remeber to prefix your field with an underscore when saving to hide it on the post/page edit screen.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/**

* @param array $post

* @param array $attachment

* @return array

*/

functionmy_image_attachment_fields_to_save($post,$attachment){

// $attachment part of the form $_POST ($_POST[attachments][postID])

// $post attachments wp post array - will be saved after returned

// $post['post_type'] == 'attachment'

if(isset($attachment['my_field'])){

// update_post_meta(postID, meta_key, meta_value);

update_post_meta($post['ID'],'_my_field',$attachment['my_field']);

}

return$post;

}

You can also add errors here that will automatically be displayed below your field in the form. The$post['errors'] array gets merged with the $form_fields array before being sent through theattachment_fields_to_edit hook.

Google is the probably best engine to be listed in. It is one of the most widely searched and they offer tools to help you in designing your page.

There are two things you need to do if you want your page listed in google.

First, submit your site name to the Google add url form. After that, I highly suggest you sign up for their sitemap program. If you need help designing your sitemap to submit, you can use mine and just edit the urls to what you want. The syntax is easy enough to understand, just replace my links with the important pages of your site. Example sitemap is as below:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?xml version="1.0"encoding="UTF-8"?>

<urlset xmlns="http://www.google.com/schemas/sitemap/0.84"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84

http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">

<url>

<loc>http://www.thedigilife.com/</loc>

<changefreq>weekly</changefreq>

<priority>0.5</priority>

</url>

<url>

<loc>http://www.thedigilife.com/example/</loc>

<changefreq>monthly</changefreq>

<priority>0.5</priority>

</url>

</urlset>

feel free to copy and paste and edit to your liking. Once you are done, place the sitemap.xml in your home directory and submit to Google. The sitemap program will tell you where your page is ranked, what search results show your page, and if your site has any errors, like broken links.

At this point, create a robots.txt file, and place it in your home directory, if you haven’t already made one.
Example robots.txt as below:

1

2

3

4

5

6

7

User-agent:*

Disallow:/design

Disallow:/africa

Sitemap:http://www.garyshood.com/sitemap.xml

user-agent:googlebot-video

Disallow:/

, when creating yours however, the only line you really need is the following:

Yahoo! is another great engine to have your page listed in. Submit your url again to Yahoo! here. Yahoo! does not have a sitemap program, but there is something similar you can do. If your website runs PHP, there is a script you can use to convert the sitemap.xml you used for Google into a map that you can use for Yahoo!. I read this article to make the yahoo.txt file that can be used as a yahoo sitemap. To do the same, below is the PHP Script.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

&lt;?php

/*

iELLIOTT.com's Google 2 Yahoo Sitemap Converter

Version: 1.0 10/31/2005

Use this script at your own risk. No Warranty or Support can be provided.

If you use this script, please give credit to iELLIOTT.com and link back to:

http://www.ielliott.com/2005/10/31/google-to-yahoo-sitemap/

This script is subject to the following license:

http://creativecommons.org/licenses/by-sa/2.5/

CUSTOMIZATION

==============

$input_file is the URL location of your exsisting Google sitemap XML file (must end with .xml)

$output_file is the name of the file you wish to write the Yahoo sitemap data to. Default is yahoo.txt, but if you've changed the name to something else, it must be reflected here (must end with .txt). Also be sure that you CHMOD your $output_file to 777 on your server.

Copy and upload it to your server in the same directory as your sitemap.xml. I found this script here. Run the script through your browser, and it will generate a file called yahoo.txt. Example yahoo.txt is as follow:

1

2

http://www.thedigilife.com/

http://www.thedigilife.com/example/

After you generate this yahoo.txt file, go to the yahoo submission url again, and for the url, put the location of your yahoo.txt and submit. Lycos is included in this because it uses the Yahoo! search engine to find websites.

MSN was the quickest to add my site to their search engine. Once again, just submit your site to the MSN add url form here. Soon, if you have AWStats setup or a similar website stat list for your page, you will notice the MSN bot has visited your page and hopefully added you to the index.

Ask Jeeves the hardest search engine to be listed in. There is no free add url form for this search engine. You do have the option of paying Ask a fee to be included in the results, but I wouldn’t suggest it, since I have gotten this site in Ask for free, it just took a lot longer. Submit your site to the Open Directory Project here. You have to pick a category for your page and provide a good description on why you should be listed to be accepted. If your site does get popular enough to be listed in the other search engines, there is still a good chance the AskJeeves bot will visit your page and include you in the search directory.

Tips To Get Listed

Content is the most important thing to get listed. Search engines will not add your page if you have an “Under Construction” or “Coming Soon” notice on every single page.

The more websites that link to your page, the faster you will get listed. Put your website in your signature in online forums that you visit.

Search engines may take up a week to list you, be patient and make sure you have some type of web stats so you can tell if the bots have visited your site yet.

I hope you all are well. Today I am going to write post on How can make to user download the file from the another website without showing them that the file is actually coming from another server?

This can help many beginners PHP User to to Hide File URL Location in PHP. Here is the example how can u fetch file from other website and give download to the user like its downloading from our website.

Find the line #LoadModule rewrite_module modules/mod_rewrite.so in the “httpd.conf” file. You can do this easily by searching the keyword “mod_rewrite” from find menu.

Uncomment the line. http.conf file use # to comment the line. So remove the # from begining of the line.

Restart the server. In WAMP you can restart the server by click the icon of WAMP in system tray in right bottom side of the windows. For XAMPP you can open XAMPP control and restart the server.

You can check the mod_rewrite is enabled using phpinfo();

Create HTACCESS file

Lets consider one real world example for creating and understading HTACCESS file and its rules. HTACCESS file uses RewriteRule for define the rule for URL rewriting. This will show you good example for regular expression, rewrite rules & conditions.

For example, create file testhtaccess.php. Write

1

"This is PHP HTACCESS Test File"

Create second file testhtaccess.html and Write

1

"This is HTML HTACCESS Test File".

This is simple text written in the both the files so that we can differentiate when we rewrite the URL which file is called.

Create Third file .htaccess in same folder of the server where these two files are and Write

1

2

RewriteEngine On

RewriteRule^/?testhtaccess\.html$testaccess.php[L]

The first line turns RewiteEnging On. It will allow the server to rewrite the URL. Second line is the rule for URL rewriting. “^/” says that from starting any type of character and any number of character are allowed. Then there is “?testhtaccess\.html” \ is for escaping the . in name and there is $ which implies that this is end for rule. This is first Parameter for RewriteRule. Now second parameter tells which files to call when url is matched.

So here when we call testaccess.html file is will be rewite the url and call testhtaccess.php file. This will done internally and URL remains the same.

Lets go now little complex for this. lets say that we have URL and Query String like as below:

Now we have to tell the apache that whenever this second rewrited url called it should internally call first URL with query string. Now for the ditails.php script to read and parse the query string, we’ll need to use regular expressions to tell mod_rewrite how to match the two URIs. For this you should have knowledge of regular expression. Even though I am going to explain some key factor of regular expression.

This will replace the Rewrite URL with Actual One. [a-zA-Z_]+ will match any string in lowercase or Uppercase. Its in small bracket ( ) so that it store its value in $1 and when it occurs second time it will store its value in $2.

This is so simple as we can see. I have written this post for the beginners like me. I written what I learn reading other forums and blog which are seems to be very complex for understanding it.

This is my first post for the blog. Recently I have worked on two large database projects on backend MySQL Database. During the period of the project I came across with many problems and somehow I managed them all.

Many of you also came across with the same MySQL Database problem with Performance. Query is not running well etc. During this period I read many blogs and forums to solve these problems. I have figured out some tips or can say some points which we should taken care of.

Database Engine (MYISAM vs. Innodb)

Both MySQL Database engines have its own pros and cons that we have to decide which type of db engine will work great for us. Below are some concerns with this two engines:

MYISAM

MYISAM use less memory

It allows full text search

It locks the table while writing

It is useful for application in which reading is high and fewer write

InnoDB

It uses more memory

It does not support full text search

InnoDB provides faster performance

It lock the table at row level while writing to the table

It works great for the application which make extensive use of read and write both

Good Database Design

Good database design is a backbone for the application performance. Bad design makes application performance less. Table must be normalized. Data Structure is the main factor which must be developed carefully. Every Developer must give time for each table and fields for making good design. You should give proper data type to each field. When you done with database creation, you would like to see what is MySQL suggest you for your database table. Here is the Command which can help you to get this information:

Indexes

What many of us is knowing that indexes help us to increase the speed of query. Many times indexes create confusion in mind. Creating of proper indexes for the table is necessary but do make table overhead of indexes as indexes take space on the disk. So it increases the workload on the disk. Working on my project I many time need to add and delete column from large table which takes so much time. For increasing performance we can make index ON of OFF. so before whenever I start my database operation I make the index key off and do the operation when operations completed I again makes indexes ON. So rather than making new indexes on my each operation, it will make new index when I male Index on so its only one time. for turning on and index I use below syntax:

1

2

Disable Indexes:ALTER TABLE table_name DISABLE KEY

Enable Indexes:ALTER TABLE table_name ENABLE KEY

Tuning MySQL

Hardware makes as important role as other things in database tuning. Our hardware needs just as much attention and tuning as our database and script does. It is also need to check MySQL Configuration file what type of changes we have make to the configuration. There is one tool available which is perl script. You can download and Install on server It tells that which type of configuration change you can make improve the performance.

Note: This are the simple things which I feel good to use and take care for better performance.