Tag Archives: wordpress hack

Wordpress security - BulletProof Security vs Better WP Security, which is the best

WordPress security – BulletProof Security vs Better WP Security, which is the best

BulletProof Security and Better WP Security both wordpress plugins are used for wordpress security purpose. Both have some nice and unique features. There are wordpress hackers and they are looking to hack your wordpress sites. You should protect your wordpress sites.

Better WP Security features:

Better WP Security takes the best WordPress security features and techniques and combines them in a single plugin thereby ensuring that as many security holes as possible are patched without having to worry about conflicting features or the possibility of missing anything on your site.

With one-click activation for most features as well as advanced features for experienced users Better WP Security can help protect any site.

Wordpress security - BulletProof Security vs Better WP Security, which is the best

WordPress security – BulletProof Security vs Better WP Security, which is the best


Obscure

As most WordPress attacks are a result of plugin vulnerabilities, weak passwords, and obsolete software. Better WP Security will hide the places those vulnerabilities live keeping an attacker from learning too much about your site and keeping them away from sensitive areas like login, admin, etc.

  • Remove the meta “Generator” tag
  • Change the urls for WordPress dashboard including login, admin, and more
  • Completely turn off the ability to login for a given time period (away mode)
  • Remove theme, plugin, and core update notifications from users who do not have permission to update them
  • Remove Windows Live Write header information
  • Remove RSD header information
  • Rename “admin” account
  • Change the ID on the user with ID 1
  • Change the WordPress database table prefix
  • Change wp-content path
  • Removes login error messages
  • Display a random version number to non administrative users anywhere version is used

Protect

Just hiding parts of your site is helpful but won’t stop everything. After we hide sensitive areas of the sites we’ll protect it by blocking users that shouldn’t be there and increasing the security of passwords and other vital information.

  • Scan your site to instantly tell where vulnerabilities are and fix them in seconds
  • Ban troublesome bots and other hosts
  • Ban troublesome user agents
  • Prevent brute force attacks by banning hosts and users with too many invalid login attempts
  • Strengthen server security
  • Enforce strong passwords for all accounts of a configurable minimum role
  • Force SSL for admin pages (on supporting servers)
  • Force SSL for any page or post (on supporting servers)
  • Turn off file editing from within WordPress admin area
  • Detect and block numerous attacks to your filesystem and database

Detect

Should all the protection fail Better WP Security will still monitor your site and report attempts to scan it (automatically blocking suspicious users) as well as any changes to the filesystem that might indicate a compromise.

  • Detect bots and other attempts to search for vulnerabilities
  • Monitor filesystem for unauthorized changes

Recover

Finally, should the worst happen Better WP Security will make regular backups of your WordPress database (should you choose to do so) allowing you to get back online quickly in the event someone should compromise your site.

  • Create and email database backups on a customizable schedule

Other Benefits

  • Make it easier for users to log into a site by giving them login and admin URLs that make more sense to someone not accustomed to WordPress
  • Detect hidden 404 errors on your site that can affect your SEO such as bad links, missing images, etc.

Compatibility

  • Works on multi-site (network) and single site installations
  • Works with Apache, LiteSpeed or NGINX (NGINX will require you to manually edit your virtual host configuration)
  • Some features can be problematic if you don’t have enough RAM to support them. All my testing servers allocate 128MB to WordPress and usually don’t have any other plugins installed. I have seen issues with file check and database backups failing on servers with 64MB or less of RAM, particularly if there are many other plugins being used.

Translations

Please let us know if you would like to contribute a translation.

Warning

Please read the installation instructions and FAQ before installing this plugin. It makes some significant changes to your database and other site files which, without a proper backup, can cause problems if something goes wrong. While problems are rare, most (not all) support requests I get for this plugin involve the users failure to make a proper backup before installing.

BulletProof Security features:

htaccess Core Website Security

WordPress Website Security Protection: BulletProof Security protects your WordPress website against XSS, RFI, CRLF, CSRF, Base64, Code Injection and SQL Injection hacking attempts. One-click .htaccess WordPress security protection. Protects wp-config.php, bb-config.php, php.ini, php5.ini, install.php and readme.html with .htaccess security protection. Security Logging. HTTP Error Logging. One-click Website Maintenance Mode (HTTP 503). Additional website security checks: DB errors off, file and folder permissions check… System Info: PHP, MySQL, OS, Server, Memory Usage, IP, SAPI, DNS, Max Upload… Built-in .htaccess file editing, uploading and downloading.

Login Security & Monitoring Website Security

Login Security & Login Monitoring: Log All User Account Logins or Log Only User Account Lockouts (see Screenshot). Email alerting options allow you to choose 5 different email alerting options: Choose to have email alerts sent when a User Account is locked out, An Administrator Logs in, An Administrator Logs in and when a User Account is locked out, Any User logs in when a User Account is locked out or Do Not Send Email Alerts. See BulletProof Security Login Security & Monitoring Features for additional features and options.

Why is .htaccess Website Security So Much Better Than Any Other Type of Website Security?

The answer is very simple – .htaccess files (distributed configuration files) are processed first before any other code on your website. In other words, hackers malicious scripts are stopped by BulletProof Security .htaccess files before those scripts even have a chance to reach the php coding in WordPress. BulletProof Security uses .htaccess website security files, which are specific to Apache Linux Servers. Please read the FAQ page for Server compatibility questions.

BulletProof Security Fast and Simple with No Manual Configuration Required

The BulletProof Security WordPress Security plugin is designed to be a fast, simple and one click security plugin to add .htaccess website security protection for your WordPress website. Activate .htaccess website security and .htaccess website under maintenance modes from within your WordPress Dashboard – no FTP required. The BulletProof Security WordPress plugin is a one click security solution that creates, copies, renames, moves or writes to the provided BulletProof Security .htaccess master files. BulletProof Security protects both your Root website folder and wp-admin folder with .htaccess website security protection, as well as providing additional website security protection.

BulletProof Security allows you to add .htaccess website security protection from within the WordPress Dashboard so that you do not have to access your website via FTP or your Web Host Control Panel in order to add website security protection for your WordPress site. BulletProof Security Modes: Root .htaccess security protection, wp-admin .htaccess security protection, Deny All .htaccess self protection, WordPress default .htaccess mode and .htaccess Maintenance Mode (503 Website Under Maintenance). In BulletProof Security Mode your WordPress website is protected from XSS, RFI, CRLF, CSRF, Base64, Code Injection and SQL Injection hacking attempts.

BulletProof Security Maintenance Mode

BulletProof Security Maintenance Mode allows you to create your custom website under maintenance page within BulletProof Security and activate Maintenance Mode to put your website in maintenance mode. Maintenance Mode allows website developers or website owners to access and work on a website while a 503 Website Under Maintenance page is displayed to all other visitors to the website. Allow access to your WordPress Dashboard for only yourself or add additional IP addresses to allow mulitple IP addresses access to your WP Dashboard while in maintenance mode.

BulletProof Security Additional Website Security Protection

WordPress is already very secure, but every website, no matter what type of platform it is built on should have additional website security measures in place as a standard. BulletProof Security provides that additional website security protection that every website should have.

Translations

  • Lithuanian by Vincent G from Host1Free.com
  • Filipino/Tagalog by pointen.dk
  • Russian by EyeFinity
  • If you would like to translate the BPS plugin to your language see this BPS Plugin Language Translation Tutorial. Please include a link to your website so that we can add it here. Thank you.
  • Tip: If you use the Google Chrome Browser you can right mouse click in plugin pages and then click on Translate to… To translate plugin text into your Language.

BulletProof Security htaccess Core Features

  • One-click .htaccess website security protection from within the WP Dashboard
  • .htaccess security protection against XSS, RFI, CRLF, CSRF, Base64, Code Injection and SQL Injection hacking attempts
  • .htaccess file backup and restore
  • .htaccess Lock / Unlock (404 Read-Only)
  • .htaccess AutoLock On or Off
  • Security / HTTP Error Logging – Log 400, 403 and 404 Errors
  • Security Log: Add / Remove User Agents/Bots to Ignore/Not Log or Allow/Log
  • Security Log: Turn On / Turn Off / Delete Log
  • Automatic .htaccess file updating on upgrade installation
  • New .htaccess security filters automatically added during upgrade
  • No need to reactivate BulletProof Modes when upgrading
  • WP Dashboard Alerts – Root and wp-admin .htaccess file checks
  • Anti Comment Spam .htaccess code – works together with Akismet or other Spam plugins to keep Comment Spam at a minimum
  • Anti Comment Spambot .htaccess code – Forbid Empty Referrer Spambots
  • TimThumb Vulnerability/Exploit .htaccess coding
  • Built-in File Editing, File Downloading and File Uploading
  • Custom Code feature that permanently saves and writes your personal custom .htaccess code
  • WordPress readme.html and /wp-admin/install.php protected with .htaccess security protection
  • wp-config.php and bb-config.php files protected with .htaccess security protection
  • php.ini and php5.ini files protected with .htaccess security protection
  • WordPress database errors turned off – Verification and function insurance
  • WordPress version is not displayed / not shown – WordPress version is removed
  • WP Generator Meta Tag filtered – not displayed / not shown
  • WP DB default admin username / account check
  • System Info: PHP, MySQL, OS, Server, Memory Usage, IP, SAPI, DNS, Max Upload, Zend Engine Version, Zend Guard/Optimizer, ionCube Loader, Suhosin, APC, eAccelerator, XCache, Varnish, cURL, Memcache and Memcached
  • Security Status Page – Displays website security status information
  • File and Folder Permission Checking – CGI / DSO SAPI check / display
  • Help & FAQ page – links to BPS Guide and other detailed Help & Info pages
  • Extensive Read Me! jQuery Dialog Help buttons throughout the BulletProof Security plugin pages
  • Backup and Restore existing .htaccess files
  • Backup and Restore customized / modified .htaccess files
  • Add to, Edit, Modify the provided BulletProof Security .htaccess Master files
  • Create your own .htaccess Master files or code and use BulletProof Security as an .htaccess file manager
  • Website Developer Maintenance Mode (503 website open to Developer / Site Owner ONLY)
  • Log in / out of your website while in Maintenance Mode
  • Customizable 503 Website Under Maintenance page
  • HUD Success / Error message display
  • i18n Language Translation coding

BulletProof Security Login Security & Monitoring Features

  • Log All User Account Logins or Log Only User Account Lockouts
  • Logged DB Fields: User ID, Username, Display Name, Email, Role, Login Time, Lockout Expires, IP Address, Hostname, Request URI
  • Email Alerting Options: User Account is locked out, An Administrator Logs in, An Administrator Logs in and when a User Account is locked out, Any User logs in when a User Account is locked out, Do Not Send Email Alerts
  • Login Security Additional Options: Max Login Attempts, Automatic Lockout Time, Manual Lockout Time, Max DB Rows To Show, Turn On/Turn Off
  • Dynamic DB Form: Lock, Unlock, Delete
  • Enhanced Search: Allows you to search all of the Login Security database rows/Fields
  • Stand-alone Unlock Form bpsunlock.php: Unlock User Accounts without having to be logged into the WP Dashboard
  • Please click the Login Security Blue Read Me help button for full descriptions of all features and options.

Conclusion: I used both the plugins for some time. I recommend to use the Better WP security plugin which 100% free and it has very great features.

Change uploaded image name to post slug during upload using variables

Change uploaded image name to post slug during upload using variables

If you want to rename files during upload and set their names to the post slug the files are beeing attached to, plus some random characters (a simple incremental counter will de just fine) to make the filenames different.

Change uploaded image name to post slug during upload using variables

Change uploaded image name to post slug during upload using variables

In other words, if you are uploading/attaching images to the post whose page slug is “test-page-slug”, i’d like for the images to be renamed on the fly to test-page-slug-[C].[original_extension] — test-page-slug-1.jpg, test-page-slug-2.jpg etc (no matter what the original filenames were).

This is very easy. You just need to use following hook in functions.php file.

function wp_modify_uploaded_file_names($image_name) {

    // Get the parent post ID, if there is one
    if( isset($_GET['post_id']) ) {
        $post_id = $_GET['post_id'];
    } elseif( isset($_POST['post_id']) ) {
        $post_id = $_POST['post_id'];
    }

    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if(is_numeric($post_id)) {

        // Get the post slug
        $post_obj = get_post($post_id); 
        $post_slug = $post_obj->post_name;

        // If we found a slug
        if($post_slug) {

            $random_number = rand(10000,99999);
            $image_name['name'] = $post_slug . '-' . $random_number . '.jpg';

        }

    }

    return $image_name;

}
add_filter('wp_handle_upload_prefilter', 'wp_modify_uploaded_file_names', 1, 1);

This is very easy.
if you have pretty permalinks enabled, so I’ve added a check to make sure there is a slug before renaming the file. You’ll also want to consider checking the file type, which I haven’t done here–I’ve just assumed it’s a jpg.

remove first image from wordpress post

Remove first image from wordpress post

In many wordpress old site they used the first image as post or featured image so while showing the single post they not want to show the first image which is uploaded.

remove first image from wordpress post

remove first image from wordpress post

Using following code you can remove the first image from wordpress post. Please put following code in to functions.php file (you will find this file in your theme folder)


function remove_first_image ($content) {
if (!is_page() && !is_feed() && !is_feed() && !is_home()) {
$content = preg_replace("/<img[^>]+\>/i", "", $content, 1);
} return $content;
}
add_filter('the_content', 'remove_first_image');

when you see the single page of blog then you will not see the first image from blog post.

 

Add Custom Content to End of RSS Post

Add Custom Content to End of RSS Post

RSS (most commonly expanded as Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.

custom meta tags
RSS feed are very important. WordPress has own wordpress api to designed many RSS feed format.
In this tutorial I will show you how to add the custom text in your rss feed.
You just need to open your functions.php file and put following code in that file.

function feed_the_Filter($query) {
if ($query->is_feed) {
add_filter('the_content','add_to_feed');
}
return $query;
}
add_filter('pre_get_posts','feed_the_Filter');

function add_to_feed($content) {
$content .= '<p>Follow us on Twitter &amp;lt;a href="http://twitter.com/wordpressapi"&amp;gt;Wordpress API&amp;lt;/a&amp;gt;</p>';
$content .= '<p>Join our &amp;lt;a href="http://www.facebook.com/pages/wordpressapi/280021545846"&amp;gt;Wordpress API Facebook Community Page&amp;lt;/a&amp;gt;</p>';

return $content;
}
Remove the upload buttons for author and other wordpress user

Remove the upload buttons for author and other wordpress user

If you want to restrict the normal author to upload media file your wordpress blog. So you can use the following code in your functions.php file.

Following function will remove the upload media button from wordpress dashboard.


//remove the upload buttons for auther and other wordpress user
function removemediabuttons()
{
if($user-&amp;gt;wp_user_level &amp;gt;= 1) {
remove_action( 'media_buttons', 'media_buttons' );
}

}
add_action('admin_head','removemediabuttons');

Following code will remove the media library tab from the Add new post section for all the users.
Restricts media library access (subscriber) under the “add new post”

function remove_medialibrary_tab($tabs) {
unset($tabs['library']);
return $tabs;
}
add_filter('media_upload_tabs','remove_medialibrary_tab');

This hack is very important for wordpress developers. when you are developing the multiuser wordpress site.

how to Hide Wordpress Dashboard Login Errors

Hide WordPress Dashboard Login Errors

how to Hide WordPress Dashboard Login Errors

how to Hide WordPress Dashboard Login Errors

Hiding wordpress dashboard login error is very basic thing for keep away hackers. Whenever you and any hackcer are trying to login using the correct username but with the wrong password, that will give you a message saying “Error: Incorrect Password.” hacker will got the clue that the username entered is in the system, and that they simply need to crack its password. Same with username also you will got following message.
“Error: Invalid username”
For avoiding this thing you just need to open your functions.php file and put the following code in that file

add_filter('login_errors', create_function('$a', "return null;"));

This hack will remove the WordPress error by displaying nothing when a login is incorrect.

 

featured-image-wordpress

How to set post first image as featured image automatically

From wordpress 3.0 version wordpress launched the feature called featured image. Many new wordpress themes are compatible with new wordpress version. So using or choosing the image as featured image for post is another manual work we need to do.

Many old wordpress website holder or blogger is having issue with this functionality. What they want is when they create the post they haven’t set the featured image, but they would like the featured image to default to the image that has been included in the post.

Some wordpress always use the first image as featured image but old post was not updated with featured image. They need to do manual work to set the featured image. I also faced same issue.

After doing some R&D I found the solution. If you want to set the your posts first image as featured image then use my following code.

For using the code you need to open your mysql database command prompt or phpmysqladmin program and select your wordpress database and execute the following query in that.

insert into wp_postmeta (meta_value, meta_key, post_id) select DISTINCT(ID), post_type , post_parent from wp_psts where post_type= 'attachment' and post_parent !=0 and post_status='inherit';<br /><br />update wp_postmeta set meta_key = '_thumbnail_id' where meta_key='attachment'

Using above sql query you will be able to set the featured image to your old and new post from post content. If you are having any issues with using this sql then write to me.

How to set post first image as featured image automatically

How to set post first image as featured image automatically

How to send smtp email through wordpress without plugin

Many people want to sent the email through smtp from wordpress. WordPress uses the PHPmailer in there CMS. But many wordpress developer dont know how to use the wordpress phpmailer functionality. Using PHPmailer you can send the email using STMP service.

Many people use the wordpress plugins for sending the email. But I recommend not to use any wordpress plugin code for this. Because many of wordpress plugin code are not necessary and that will not useful for your wordpress application.

Here in this article I will show you how to sent email using wordpress with SMTP settings.

Use the following code for this:


// SMTP email sent
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer();
$phpmailer->SMTPAuth = true;
$phpmailer->Username = 'Username';
$phpmailer->Password = 'password';

$phpmailer->IsSMTP(); // telling the class to use SMTP
$phpmailer->Host       = "hostname.com"; // SMTP server
$phpmailer->FromName   = $_POST[your_email];
$phpmailer->Subject    = $_POST[your_subject];
$phpmailer->Body       = $_POST[your_message];                      //HTML Body
$phpmailer->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$phpmailer->WordWrap   = 50; // set word wrap
$phpmailer->MsgHTML($_POST[your_message]);
$phpmailer->AddAddress('support@wordpressapi.com/files/', 'Wordpress support');
//$phpmailer->AddAttachment("images/phpmailer.gif");             // attachment
if(!$phpmailer->Send()) {
 echo "Mailer Error: " . $phpmailer->ErrorInfo;
} else {
 echo "Message sent!";
}

Use the above code for sending the email from wordpress. With godaddy hosting service above code is very useful for creating the contact us page.

Many wp developers asked me where to add the above code. So here is answer. You can create wordpress theme template page. Like contact us page and add the above code in that page according to your requirement.

If you are having any issues or question about using the code then please write to me.

File upload with add_meta_box or custom_post_type in wordpress

From wordpress 3.0 version wordpress introduced the custom_post_type function. Many people want to attach the file field with add_meta_box function. In this tutorial I will tell you how to upload file with custom meta box and post type. I tested above code with new wordpress versions 3.9. Still code is working fine.

In this tutorial I will show you how to create the custom post type and add custom meta boxes to that post type and upload file with custom meta box.

After digging into wordpress files and functions I created following code. Just open your functions.php file and put following code in that file for creating custom post type.


<?php
 add_action('init', 'create_product');
 function create_product() {
 $product_args = array(
 'label' => __('Product'),
 'singular_label' => __('Product'),
 'public' => true,
 'show_ui' => true,
 'capability_type' => 'post',
 'hierarchical' => false,
 'rewrite' => true,
 'supports' => array('title', 'editor', 'thumbnail')
 );
 register_post_type('product',$product_args);
 }
?>

For uploading the file through custom meta box use the following code. Following code will add the file field to custom meta box and you are able to upload file or image to wordpress and upload file attachment to you custom post. Following code is very helpful to many wordpress theme and plugin developer. If you are having any issues or trouble using code then get back to me.

File upload with add_meta_box or custom_post_type in wordpress

File upload with add_meta_box or custom_post_type in wordpress


<?php

 add_action("admin_init", "add_product");
 add_action('save_post', 'update_purchase_url');
 function add_product(){
 add_meta_box("product_details", "product Options", "product_options", "product", "normal", "low");
 }
 function product_options(){
 global $post;
 $custom = get_post_custom($post->ID);
 $purchase_url = $custom["purchase_url"][0];
 $product_price = $custom["product_price"][0];
 $product_image = $custom["product_image"][0];
 $video_code = $custom["video_code"][0];

?>
 <div id="product-options">
 <label>Purchase URL:</label><input size="100" name="purchase_url" value="<?php echo $purchase_url; ?>" /><br>
 <label>Product Price:</label><input size="100" name="product_price" value="<?php echo $product_price; ?>" /><br>
 <label>Product Image:</label><input type="file" size="100" name="product_image" value="<?php echo $product_image; ?>" />
 <img src="<?php echo $product_image; ?>"><br>

 </div><!--end product-options-->
<?php
 }
 function update_purchase_url(){
 global $post;
 update_post_meta($post->ID, "purchase_url", $_POST["purchase_url"]);
 update_post_meta($post->ID, "product_price", $_POST["product_price"]);
 update_post_meta($post->ID, "product_image", $_POST["product_image"]);

 if(!empty($_FILES['product_image']['name'])){ //New upload
 require_once( ABSPATH . 'wp-admin/includes/file.php' );
 $override['action'] = 'editpost';

 $uploaded_file = wp_handle_upload($_FILES['product_image'], $override);

 $post_id = $post->ID;
 $attachment = array(
 'post_title' => $_FILES['product_image']['name'],
 'post_content' => '',
 'post_type' => 'attachment',
 'post_parent' => $post_id,
 'post_mime_type' => $_FILES['product_image']['type'],
 'guid' => $uploaded_file['url']
 );
 // Save the data
 $id = wp_insert_attachment( $attachment,$_FILES['product_image'][ 'file' ], $post_id );
 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $_FILES['product_image']['file'] ) );

update_post_meta($post->ID, "product_image", $uploaded_file['url']);
 }
 }
?>

For Uploading the file your post form need to add the enctype=”multipart/form-data” type to your form. Just use the following code in your functions.php file.

1

<?php
function fileupload_metabox_header(){
?>
<script type="text/javascript">
 jQuery(document).ready(function(){
 jQuery('form#post').attr('enctype','multipart/form-data');
 jQuery('form#post').attr('encoding','multipart/form-data');
 });
</script>
<?php }
add_action('admin_head', 'fileupload_metabox_header');

?>

For checking all information in edit or preview section use following code.


<?php

add_action("manage_posts_custom_column",  "product_custom_columns");
add_filter("manage_edit-product_columns", "product_edit_columns");

function product_edit_columns($columns){
 $columns = array(
 "cb" => "<input type=\"checkbox\" />",
 "title" => "Product Title",
 "purchase_url" => "Purchase URL",
 "product_price" => "Product Price",
 "product_image" => "Product Image",
 );
 return $columns;
}
function product_custom_columns($column){
 global $post;
 switch ($column) {
 case "purchase_url":
 $custom = get_post_custom();
 echo $custom["purchase_url"][0];
 break;
 case "product_price":
 $custom = get_post_custom();
 echo $custom["product_price"][0];
 break;
 case "product_image":
 $custom = get_post_custom();
 $img_url =$custom["product_image"][0];
 echo "<image src=".$img_url." height=100 width=100 />";
 break;
 }
}

?>

Above code is useful for any type of customization. If you are having any issue with using this code then please get back to me.

How to use the custom post type in wordpress 3.0

From wordpress 3.0 version release wordpress gives the facility to add a custom post type functionality. With custom post type wordpress is became more powerful and expendable and more advanced. WordPress recognized the need to people and industry and they introduced the custom post type. In this tutorial I will tell you how to use the custom post type very effectively.

Adding Custom post type is very easy. Using theme or plugin file you can add the custom post types in wordpress admin area.

Here I am going to give you example using wordpress theme files. Open you functions.php file and copy paste the following code in that file.


add_action('init', 'create_product');
 function create_product() {
 $product_args = array(
 'label' => __('Product'),
 'singular_label' => __('Product'),
 'public' => true,
 'show_ui' => true,
 'capability_type' => 'post',
 'hierarchical' => false,
 'rewrite' => true,
 'supports' => array('title', 'editor', 'thumbnail')
 );
 register_post_type('product',$product_args);
 }

The function register_post_type() accepts two arguments: the name we want to give our post type, and a list of arguments used to create that post type, which we put in an array called $args.

Using above code that code will add the product post type to wordpress panel.

Now you can add the meta fields to custom post type. Use the following code in file for add the meta fields. Custom meta fields function is available from quite some time. add_meta_box() function is very useful to adding custom fields to wordpress post.


<?php

 add_action("admin_init", "add_product");
 add_action('save_post', 'update_thumbnail_url');
 function add_product(){
 add_meta_box("product_details", "product Options", "product_options", "product", "normal", "low");
 }
 function product_options(){
 global $post;
 $custom = get_post_custom($post->ID);
 $thumbnail_url = $custom["thumbnail_url"][0];
 $product_info = $custom["product_info"][0];
 $product_infos = $custom["product_infos"][0];
 $video_code = $custom["video_code"][0];

?>
 <div id="product-options">
 <label>Thumbnail URL:</label><input size="100" name="thumbnail_url" value="<?php echo $thumbnail_url; ?>" /><br>
 <label>Product Info:</label><input size="100" name="product_info" value="<?php echo $product_info; ?>" /><br>
 <img src="<?php echo $product_infos; ?>"><br>
 <label>Video Code:</label><textarea cols="50" rows="5" name="video_code"><?php $video_code; ?></textarea>
 </div><!--end product-options-->
<?php
 }
 function update_thumbnail_url(){
 global $post;
 update_post_meta($post->ID, "thumbnail_url", $_POST["thumbnail_url"]);
 update_post_meta($post->ID, "product_info", $_POST["product_info"]);
 update_post_meta($post->ID, "video_code", $_POST["video_code"]);

 }
?>

Using following code you can see the product information in edit product page and you can able to see the all information in for edit. Admin will know which fields are available to edit.


<?php
add_action("manage_posts_custom_column",  "product_custom_columns");
add_filter("manage_edit-product_columns", "product_edit_columns");

function product_edit_columns($columns){
 $columns = array(
 "cb" => "<input type=\"checkbox\" />",
 "title" => "Product Title",
 "thumbnail_url" => "Thumbnail URL",
 "product_info" => "Product Info",
 "video_code" => "Video Code",
 );
 return $columns;
}
function product_custom_columns($column){
 global $post;
 switch ($column) {
 case "thumbnail_url":
 $custom = get_post_custom();
 echo $custom["thumbnail_url"][0];
 break;
 case "product_info":
 $custom = get_post_custom();
 echo $custom["product_info"][0];
 break;
 case "video_code":
 $custom = get_post_custom();
 echo $custom["video_code"][0];
 break;
 }
}

?>

Using custom post type and add meta tag you can develop very nice applications. Now I am going to show you how you can extract the custom posts in wordpress frontend.

Using wp_query you can easily extract product posts. In any category page or conditionally you can use following code.


$loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => 10 ) );
while ( $loop->have_posts() ) : $loop->the_post();
 the_title();
the_content();
global $post;
 $custom = get_post_custom($post->ID);
echo $thumbnail_url = $custom["thumbnail_url"][0];
echo $product_info = $custom["product_info"][0];
echo $video_code = $custom["video_code"][0];
 echo '<div>';
 the_content();
 echo '</div>';
endwhile;

Or you can create the custom theme page using following code. Just create product.php page in your wordpress theme folder.Put following code in that file.


<?php

/*Template Name: Product*/

?>

<?php get_header(); ?>

<div id="container">

<div id="content" role="main">

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>

<?php $recent = new WP_Query('post_type=product&posts_per_page=10′); while($recent->have_posts()) : $recent->the_post();?>

<?php the_title( '<h2><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0′ ) . '" rel="bookmark">', '</a></h2>' ); ?>

<div>

<?php the_content(); ?>

<?php

the_content();
global $post;
$custom = get_post_custom($post->ID);
echo $thumbnail_url = $custom["thumbnail_url"][0];
echo $product_info = $custom["product_info"][0];
echo $video_code = $custom["video_code"][0];

?>

<?php wp_link_pages( array( 'before' => '<div>' . __( 'Pages:', 'wordpressapi' ), 'after' => '</div>' ) ); ?>

<?php edit_post_link( __( 'Edit', 'wordpressapi' ), '<span>', '</span>' ); ?>

</div><!– .entry-content –>

<?php comments_template( ", true ); ?>

<?php endwhile; ?>

</div><!– #content –>

</div><!– #container –>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Now create product page and product as template.

If you have any issues or doubts then write to me.