PHP Developer

Wednesday, 16 December 2015

Wordpress Plugin to Create Custom Registration form Plugin

Wordpress Plugin to Create Custom Registration form Plugin :


<?php

/*
  Plugin Name: Custom Registration Form
  Plugin URI: http://astro-global.blogspot.in/
  Description: Updates user rating based on number of posts.
  Version: 1.0
  Author: Sunil Sharma
  Author URI: https://plus.google.com/u/0/+SunilSharma_007
 */


function custom_registration_function() {
    if (isset($_POST['submit'])) {
        registration_validation(
        $_POST['username'],
        $_POST['password'],
        $_POST['email'],
        $_POST['website'],
        $_POST['fname'],
        $_POST['lname'],
        $_POST['nickname'],
        $_POST['bio']
        );
       
        // sanitize user form input
        global $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio;
        $username    =     sanitize_user($_POST['username']);
        $password     =     esc_attr($_POST['password']);
        $email         =     sanitize_email($_POST['email']);
        $website     =     esc_url($_POST['website']);
        $first_name =     sanitize_text_field($_POST['fname']);
        $last_name     =     sanitize_text_field($_POST['lname']);
        $nickname     =     sanitize_text_field($_POST['nickname']);
        $bio         =     esc_textarea($_POST['bio']);

        // call @function complete_registration to create the user
        // only when no WP_error is found
        complete_registration(
        $username,
        $password,
        $email,
        $website,
        $first_name,
        $last_name,
        $nickname,
        $bio
        );
    }

    registration_form(
        $username,
        $password,
        $email,
        $website,
        $first_name,
        $last_name,
        $nickname,
        $bio
        );
}

function registration_form( $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio ) {
    echo '
    <style>
    div {
        margin-bottom:2px;
    }
   
    input{
        margin-bottom:4px;
    }
    </style>
    ';

    echo '
    <form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
    <div>
    <label for="username">Username <strong>*</strong></label>
    <input type="text" name="username" value="' . (isset($_POST['username']) ? $username : null) . '">
    </div>
   
    <div>
    <label for="password">Password <strong>*</strong></label>
    <input type="password" name="password" value="' . (isset($_POST['password']) ? $password : null) . '">
    </div>
   
    <div>
    <label for="email">Email <strong>*</strong></label>
    <input type="text" name="email" value="' . (isset($_POST['email']) ? $email : null) . '">
    </div>
   
    <div>
    <label for="website">Website</label>
    <input type="text" name="website" value="' . (isset($_POST['website']) ? $website : null) . '">
    </div>
   
    <div>
    <label for="firstname">First Name</label>
    <input type="text" name="fname" value="' . (isset($_POST['fname']) ? $first_name : null) . '">
    </div>
   
    <div>
    <label for="website">Last Name</label>
    <input type="text" name="lname" value="' . (isset($_POST['lname']) ? $last_name : null) . '">
    </div>
   
    <div>
    <label for="nickname">Nickname</label>
    <input type="text" name="nickname" value="' . (isset($_POST['nickname']) ? $nickname : null) . '">
    </div>
   
    <div>
    <label for="bio">About / Bio</label>
    <textarea name="bio">' . (isset($_POST['bio']) ? $bio : null) . '</textarea>
    </div>
    <input type="submit" name="submit" value="Register"/>
    </form>
    ';
}

function registration_validation( $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio )  {
    global $reg_errors;
    $reg_errors = new WP_Error;

    if ( empty( $username ) || empty( $password ) || empty( $email ) ) {
        $reg_errors->add('field', 'Required form field is missing');
    }

    if ( strlen( $username ) < 4 ) {
        $reg_errors->add('username_length', 'Username too short. At least 4 characters is required');
    }

    if ( username_exists( $username ) )
        $reg_errors->add('user_name', 'Sorry, that username already exists!');

    if ( !validate_username( $username ) ) {
        $reg_errors->add('username_invalid', 'Sorry, the username you entered is not valid');
    }

    if ( strlen( $password ) < 5 ) {
        $reg_errors->add('password', 'Password length must be greater than 5');
    }

    if ( !is_email( $email ) ) {
        $reg_errors->add('email_invalid', 'Email is not valid');
    }

    if ( email_exists( $email ) ) {
        $reg_errors->add('email', 'Email Already in use');
    }
   
    if ( !empty( $website ) ) {
        if ( !filter_var($website, FILTER_VALIDATE_URL) ) {
            $reg_errors->add('website', 'Website is not a valid URL');
        }
    }

    if ( is_wp_error( $reg_errors ) ) {

        foreach ( $reg_errors->get_error_messages() as $error ) {
            echo '<div>';
            echo '<strong>ERROR</strong>:';
            echo $error . '<br/>';

            echo '</div>';
        }
    }
}

function complete_registration() {
    global $reg_errors, $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio;
    if ( count($reg_errors->get_error_messages()) < 1 ) {
        $userdata = array(
        'user_login'    =>     $username,
        'user_email'     =>     $email,
        'user_pass'     =>     $password,
        'user_url'         =>     $website,
        'first_name'     =>     $first_name,
        'last_name'     =>     $last_name,
        'nickname'         =>     $nickname,
        'description'     =>     $bio,
        );
        $user = wp_insert_user( $userdata );
        echo 'Registration complete. Goto <a href="' . get_site_url() . '/wp-login.php">login page</a>.';  
    }
}

// Register a new shortcode: [cr_custom_registration]
add_shortcode('cr_custom_registration', 'custom_registration_shortcode');

// The callback function that will replace [book]
function custom_registration_shortcode() {
    ob_start();
    custom_registration_function();
    return ob_get_clean();
}

?>

 

Plugin Usage :

To implement the plugin in a WordPress post or page, use the shortcode[cr_custom_registration].
To implement the registration form in a specific aspect of your theme, add the following template tag - <?php custom_registration_function(); ?>.
You can get the plugin file from the attachment in this article.

Monday, 14 December 2015

Get product category list in woocommerce Wordpress

Get product category list in woocommerce :

<?php
echo "<div class='product_cat_sidebar'>";
echo "<h4>Wholesale Categories</h4>";
$taxonomy     = 'product_cat';
  $orderby      = 'ID';
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no
  $title        = '';
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'order'      => "asc",
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
$all_categories = get_categories( $args );
echo "<ul class='sidebar_cat'>";
foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;
        if(isset($_GET["product_cat"]) && $cat->slug == $_GET["product_cat"]){
            echo '<li class="active_category"><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a></li>';
        } else {
            echo '<li><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a></li>';
        }
      

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            } 
        }
    }
}
echo "</ul>";
echo "</div>";

?>

Thursday, 5 November 2015

How To increase Website Page load Speed in Wordpress

How To increase Website Page load Speed in Wordpress


Follow below steps and check speed in GTmetrix

Step 1 : Install and Activate two plugins from back end and adjust settings

  1. W3 Total Cache
  2. Autoptimize

Step 2 : Add this code in .htaccess file for boost website speed

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /bobymason/aceofdiamond/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
# BEGIN W3TC Browser Cache
<IfModule mod_deflate.c>
    <IfModule mod_headers.c>
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
        AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json
    <IfModule mod_mime.c>
        # DEFLATE by extension
        AddOutputFilter DEFLATE js css htm html xml
    </IfModule>
</IfModule>
# END W3TC Browser Cache

# BEGIN Expire headers
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 5 seconds"
ExpiresByType image/x-icon "access plus 2500000 seconds"
ExpiresByType image/jpeg "access plus 2500000 seconds"
ExpiresByType image/png "access plus 2500000 seconds"
ExpiresByType image/gif "access plus 2500000 seconds"
ExpiresByType application/x-shockwave-flash "access plus 2500000 seconds"
ExpiresByType text/css "access plus 600000 seconds"
ExpiresByType text/javascript "access plus 200000 seconds"
ExpiresByType application/javascript "access plus 200000 seconds"
ExpiresByType application/x-javascript "access plus 200000 seconds"
ExpiresByType text/html "access plus 600 seconds"
ExpiresByType application/xhtml+xml "access plus 600 seconds"
</IfModule>
# END Expire headers

# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
  <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(css)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(js)$">
    Header set Cache-Control "private"
  </filesMatch>
  <filesMatch "\.(x?html?|php)$">
    Header set Cache-Control "private, must-revalidate"
  </filesMatch>
</ifModule>
# END Cache-Control Headers

<ifModule mod_headers.c>
 Header set Connection keep-alive
</ifModule>
<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

Monday, 12 October 2015

How can I change email Notification for new user in WordPress

When admin add a new customer from back end manualy the email notification goes to new user.

The new user notification email is created and sent by the function wp_new_user_notification(), found in wp-includes/plugable.php

There is no filter hook within this funciton that will allow you to manipulate the output of the email, however you can of course overwrite any pluggable function via a plugin.

Note - You can only overwrite pluggable functions from within a plugin, not from within your theme.

This code will create the plugin which will be used instead of the one in wp-includes/plugable.php


<?php
/**
 * Plugin Name: User Email Notification
 * Plugin URI: http://astro-global.blogspot.in/
 * Description: This plugin helps you to Send email notification to user if user create by admin in back end. Easily customize, send Username, Password and link also.
 * Version: 1.0.0
 * Author: Sunil Sharma
 * Author URI: https://plus.google.com/u/0/+SunilSharma_007
 */

$pathsss = $_SERVER['DOCUMENT_ROOT'];
if(!defined('DS')){
    define('DS',DIRECTORY_SEPARATOR);
}
include_once $_SERVER['DOCUMENT_ROOT'].'/wp-load.php';
function email_notification_activation()
{
    if ( ! current_user_can( 'activate_plugins' ) )
        return;
}
function email_notification_deactivation()
{
    if ( ! current_user_can( 'activate_plugins' ) )
        return;
}
function email_notification_uninstall()
{
    if ( ! current_user_can( 'activate_plugins' ) )
        return;
}
register_activation_hook( __FILE__, 'email_notification_activation' );
register_deactivation_hook( __FILE__, 'email_notification_deactivation' );
register_uninstall_hook( __FILE__, 'email_notification_uninstall' );

if ( !function_exists('wp_new_user_notification') ) :
/**
 * Pluggable - Email login credentials to a newly-registered user
 *
 * A new user registration notification is also sent to admin email.
 *
 * @since 2.0.0
 *
 * @param int    $user_id        User ID.
 * @param string $plaintext_pass Optional. The user's plaintext password. Default empty.
 */

function wp_new_user_notification($user_id, $plaintext_pass = '') {
    $user = get_userdata( $user_id );

    // The blogname option is escaped with esc_html on the way into the database in sanitize_option
    // we want to reverse this for the plain text arena of emails.

    $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

    $message  = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
    $message .= sprintf(__('E-mail: %s'), $user->user_email) . "\r\n";

    @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);

    if ( empty($plaintext_pass) )
        return;

    $message  = sprintf(__('Username: %s'), $user->user_login) . "\r\n";
    $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
    //$message .= wp_login_url() . "\r\n";
    $message .= site_url() . "/sign-in/";

    wp_mail($user->user_email, sprintf(__('[%s] Your username and password'), $blogname), $message);

}
endif;
?>

Wednesday, 1 July 2015

Export post in CSV Format

Export post in CSV Format :

This plugin helps you to Export custom post with CSV file. CSV file include full data of custom post like featured image link, custom meta box value, title, content, etc.


<?php
/**
 * Plugin Name: Export Cause with CSV File
 * Plugin URI: https://plus.google.com/u/0/115833273431242118637
 * Description: This plugin helps you to Export Cause (custom post) with CSV file. CSV file include full data of Cause(custom post) like featured image link, custom meta box value, title, content, etc.
 * Version: 1.0.0
 * Author: Sunil Sharma
 * Author URI: http://astro-global.blogspot.in/
 */

$pathss = $_SERVER['DOCUMENT_ROOT'];
if(!defined('DS')){
    define('DS',DIRECTORY_SEPARATOR);
}
include_once $_SERVER['DOCUMENT_ROOT'].'/wp-load.php';

Thursday, 25 June 2015

Create a Custom “Lost Password” Email in WordPress

Create a Custom “Lost Password” Email in WordPress : 

We’ve all done it. Not being able to remember passwords is one of the most annoying things about having so many website accounts across the internet. Fortunately, browsers nowadays let you save usernames and passwords for most websites so you don’t have to worry about losing login information that much. However, it does still happen. If you allow user registration on your WordPress site, users will inevitably need to reset their password at some point.
WordPress provides a default password-reset process that involves the user entering their username or email into a form. Once the form is submitted, WordPress sends an email to the user with that username/password that contains a link to reset their password. Once reset, the user can log in using their new password. The thing is that the canned email for this purpose is rather plain. The bright side, though, is that, like most things, WordPress gives us a way to customize this email. The code below does the following:
  1. Changes the “From” email address. This would be the email any reply is sent to.
  2. Changes the “From” name. This shows the recipient who the email is from.
  3. Changes the email subject.
  4. Changes the content type of the email to HTML so we can use markup within the message. Before, it was a plain-text message.
  5. Creates a custom message to use in the email body. This process involves retrieving the user’s data based on their email/username, assembling a URL with appropriate query arguments so WordPress can do the password reset, and adding a custom message with the link to reset the password. The only part you’ll change is the message at the bottom; almost everything else needs to remain the same to work. Just make sure to include the link that lets the user actually reset the password.

Add this code in functions.php :
  1. <?php
    //* Change "From" email address
    add_filter( 'wp_mail_from', function( $email ) {
        return 'hello@mydomain.com';
    });
    //* Change "From" email name
    add_filter( 'wp_mail_from_name', function( $name ) {
        return 'My Website';
    });
    //* Change Subject
    add_filter( 'retrieve_password_title', function() {
        return 'Password Recovery';
    });
    //* Change email type to HTML
    add_filter( 'wp_mail_content_type', function( $content_type ) {
        return 'text/html';
    });

Wednesday, 24 June 2015

Select Subscriber and Admin Users as author of post in admin panel

 Select Subscriber and Admin Users as author of post in admin panel : 


In this select a subscriber or admin an author of a post in the admin so it displays their name as having written the post.

Add this code in functions.php file, then all users with role subscriber or administrator is show in dropdown in Author section of post

Add this code in functions.php file : 

<?php
add_filter('wp_dropdown_users', 'MySwitchUser');
function MySwitchUser($output)
{
//global $post is available here, hence you can check for the post type here
global $post;
$roles = array('administrator', 'editor', 'author', 'contributor', 'subscriber', 'byt_frontend_contributor', 'customer', 'shop_manager', 'pending');

$output = "<select id=\"post_author_override\" name=\"post_author_override\" class=\"\">";
foreach($roles as $role){
$users = get_users('role='.$role);
foreach($users as $user)
{
global $post;
$sel = ($post->post_author == $user->ID)?"selected='selected'":'';
$output .= '<option value="'.$user->ID.'"'.$sel.'>'.$user->user_login.'</option>';
}
}
//Leave the admin in the list    
    $output .= "</select>";

    return $output;
}
?>

Thursday, 9 April 2015

Create Custom Post with all options like Category, Featured image, Excerpt etc. in wordpress

Create Custom Post with all options like Category, Featured image, Excerpt etc. in WordPress


Copy and Paste this code in function.php file. This function create a post of type "servicerequest".

<?php
/*------------------------ Create Custom Post servicerequest START -------------------------------*/

function service_request() {
    $labels = array(
    'name' => 'Services',
    'singular_name' => 'Services',
    'add_new' => 'Add New Services',
    'add_new_item' => 'Add New Services',
    'edit_item' => 'Edit Services',
    'new_item' => 'New Services',
    'all_items' => 'All Services',
    'view_item' => 'View Services',
    'search_items' => 'Search Services',
    'not_found' => 'No Services Found',
    'not_found_in_trash' => 'No Services found in Trash',
    'parent_item_colon' => '',
    'menu_name' => 'Request Services',
    );
    //register_post_type is use to create new post type.
    //"servicerequest" is a post type

    register_post_type( 'servicerequest', array(
        'labels' => $labels,
        'has_archive' => true,
        'public' => true,
        'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail', 'author', 'revisions', 'post-formats' ),
        'exclude_from_search' => false,
        'capability_type' => 'post',
    )
    );  
}
add_action( 'init', 'service_request' );

Wednesday, 8 April 2015

Send Email to multiple users when custom post or post is publish by admin

Send Email to multiple users when custom post or post is publish by admin

Step 1 .  Download PHPMailer from Download and save extract file on path "/wp-content/themes/funding_press" with directory name "PHPMailer".


Step 2 .  Paste this code in function.php file.

Add Meta Box Wordpress Editor for Post or Custom Post in Wordpress

Add Meta Box Wordpress Editor for Post or Custom Post in Wordpress

<?php
/*-------- Add Meta Box Wordpress Editor for Post Code START ----------*/

function myplugin_add_custom_box() {
    $screens = array( 'post' );  // Post Type
    foreach ( $screens as $screen ) {
        add_meta_box(
            'myplugin_sectionid',
            __( 'Product Detail', 'myplugin_textdomain' ),
            'myplugin_inner_custom_box',
            $screen
        );
    }
}

Saturday, 4 April 2015

Create a plugin in wordpress to add Multiple Number of posts, Meta Box And Featured Image from CSV

Create a plugin in wordpress to add Multiple Number of posts, Meta Box And Featured Image from CSV

1.  Create a directory with name “csv-upload”.
2.  Create files in directory  “csv-upload”
          a. csv-upload -> csv-upload.php
          b. csv-upload -> csv_queryupload.php
          c. csv-upload -> ajax-loader.gif
          d. csv-upload -> csv      //This the directory where csv file upload

Tuesday, 31 March 2015

Create Template page to show all posts with pagination

Create Template page to show all posts with pagination


STEP 1.  Upload wordpress simple pagination plugin and activete it (https://wordpress.org/plugins/simple-pagination/)

STEP 2. Copy below code as a template page.

<?php
/*
* Template name: All Posts page
*/

?>

<?php get_header();?>

<div class="pop_cause all_cause">
    <h4>All Posts</h4>

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>
    <?php $temp = $wp_query;
    $wp_query= null;
    $wp_query = new WP_Query();
    $wp_query->query('posts_per_page=20&post_type=project'.'&paged='.$paged);
    ?>
    <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
        <h5><?php the_title();?></h5>
    <?php endwhile; ?>

    <?php if(function_exists('wp_simple_pagination')) { wp_simple_pagination(); }  ?>  //This function is use to show pagination and is exist in Simple Pagination Plugin
    <?php $wp_query = null; $wp_query = $temp;?>
</div> 

<?php get_footer(); ?>