Sunday, May 31, 2015

wordpress plugin for create custom category type and post type

<?php
/*
Plugin Name: MK custom texonomy and post type
Plugin URI: https://www.google.com/
Description: Admin can create its custom category and posts and view on frontend side.
Author: Mayank Patel
Version: 1.0.8
Author URI: http://www.google.com/
Text Domain: cpt-plugin
Domain Path: /languages
License: GPLv2
*/

function my_custom_post_article() {
  $args = array();
  register_post_type( 'article', $args );
}
add_action( 'init', 'my_custom_post_article' );

function my_custom_post_articles() {
  $labels = array(
    'name'               => _x( 'Articles', 'post type general name' ),
    'singular_name'      => _x( 'Article', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'book' ),
    'add_new_item'       => __( 'Add New Article' ),
    'edit_item'          => __( 'Edit Article' ),
    'new_item'           => __( 'New Article' ),
    'all_items'          => __( 'All Articles' ),
    'view_item'          => __( 'View Article' ),
    'search_items'       => __( 'Search Articles' ),
    'not_found'          => __( 'No article found' ),
    'not_found_in_trash' => __( 'No article found in the Trash' ),
    'parent_item_colon'  => '',
    'menu_name'          => 'Article'
  );
  $args = array(
    'labels'        => $labels,
    'description'   => 'Holds our article and article specific data',
    'public'        => true,
    'menu_position' => 5,
   'supports'      => array( 'title','author', 'editor','thumbnail','trackbacks' ,'excerpt','comments' ,'custom-fields','revisions','page-attributes','post-formats'),
    'has_archive'   => true,
  );
  register_post_type( 'article', $args );
}
add_action( 'init', 'my_custom_post_articles' );


function my_updated_messages( $messages )
{
  global $post, $post_ID;
  $messages['article'] = array(
    0 => '',
    1 => sprintf( __('Article updated. <a href="%s">View article</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Article updated.'),
    5 => isset($_GET['revision']) ? sprintf( __('Article restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Article published. <a href="%s">View article</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Article saved.'),
    8 => sprintf( __('Article submitted. <a target="_blank" href="%s">Preview article</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Article scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview article</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Article draft updated. <a target="_blank" href="%s">Preview article</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
  );
  return $messages;
}
add_filter( 'post_updated_messages', 'my_updated_messages' );

function my_taxonomies_article()
{
 // Hirarchical false = tags and true = categories
 register_taxonomy("article_category", array("article"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Article", "rewrite" => true));
 register_taxonomy("article_tags", array("article"), array("hierarchical" => false, "label" => "Tags", "singular_label" => "tags", "rewrite" => true));
}

add_action( 'init', 'my_taxonomies_article',0);

Wordpress to display query post lists arguments on frontend side.

$args = array(
'category__and' => array(1,3), // finding categories 1 & 3
'posts_per_page' => 10,
//'posts_per_page' => -1 , // fetch all posts from db
'year' => 2015,
'monthnum' => 05,
'orderby' => 'title',
'post_type' => 'post',
'category_name' => 'my-category-slug', // finding only current slug category posts
'order' => 'DESC'
);


//Starting with version 4.1, meta_query clauses can be nested in order to construct complex queries. For example, "show me productss where color=orange OR color=red&size=small" translates to the following:
$args = array(
'post_type'  => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key'     => 'color',
'value'   => 'orange',
'compare' => '=',
),
                array(
                        'relation' => 'AND',
                        array(
                                'key' => 'color',
                                'value' => 'red',
                                'compare' => '=',
                        ),
                        array(
                                'key' => 'size',
                                'value' => 'small',
                                'compare' => '=',
                        ),
),
),
);
$query = new WP_Query( $args );






$args = array(
'post_type'  => 'my_custom_post_type',
'meta_key'   => 'age',
'orderby'    => 'meta_value_num',
'order'      => 'ASC',
'meta_query' => array(
array(
'key'     => 'age',
'value'   => array( 3, 4 ),
'compare' => 'IN',
),
),
);
$query = new WP_Query( $args );

//Return posts between 9AM to 5PM on weekdays
$args = array(
'date_query' => array(
array(
'hour'      => 9,
'compare'   => '>=',
),
array(
'hour'      => 17,
'compare'   => '<=',
),
array(
'dayofweek' => array( 2, 6 ),
'compare'   => 'BETWEEN',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );






$paged = ( isset( $_GET['pg'] ) && intval( $_GET['pg'] ) > 0 )? intval( $_GET['pg'] ) : 1;
$query_args = array(
'post_type' => 'post',
'paged' => $paged,
'posts_per_page' => 1
);
query_posts( $query_args );

how to get Wordpress current user and user id?

$current_user = wp_get_current_user();
$current_user_name = $current_user->user_login ;

$user_id = get_current_user_id();

How to create custom registration page on frontend side in wordpress?

1) On index.php below get_header();

<?php
            if(!is_user_logged_in())
{
    ?>
    <script>window.location.href = '<?php echo home_url()."/login";?>';</script>
    <?php
    //wp_redirect(home_url()."/login");
}   
?>

2)Create file name "custom-register.php" and paste the following
<?php
/**
 * Template Name: Register Page
 *
 */
get_header();
?>
<?php
function registrationForm() {

            require_once(ABSPATH . WPINC . '/registration.php');
            global $wpdb, $user_ID;
            //Check whether the user is already logged in
            if ($user_ID)
            {
                header( 'Location:' . home_url());
            }
            else
            {
                $errors = array();

                if( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['signup'])) {
           
                    // Check username is present and not already in use
                    $username = $wpdb->escape($_REQUEST['username']);
                    if ( strpos($username, ' ') !== false ) {
                        $errors[] = "Sorry, no spaces allowed in usernames";
                    }
                    if(empty($username)) {
                        $errors[] = "Please enter a username";
                    } elseif( username_exists( $username ) ) {
                        $errors[] = "Username already exists, please try another";
                    }
           
                    // Check email address is present and valid
                    $email = $wpdb->escape($_REQUEST['email']);
                    if( !is_email( $email ) ) {
                        $errors[] = "Please enter a valid email";
                    } elseif( email_exists( $email ) ) {
                        $errors[] = "This email address is already in use";
                    }
           
                    // Check password is valid
                    if(0 === preg_match("/.{6,}/", $_POST['password'])){
                      $errors[] = "Password must be at least six characters";
                    }
                   
                    if(0 === count($errors)) {
           
                        $password = $_POST['password'];
                        
                         $new_user_id = wp_create_user( $username, $password, $email );
                       
                        global $wpdb;
                           $url = home_url();
                            $to = $email;
                            $subject = "New Account Verification";

                            $header .= "Reply-To: <test@test.org>\r\n";
                                                        $header .= "Return-Path: <testteam@test.org>\r\n";
                            $headers = "From: ePray Team <test@test.org> \r\n";
                                                        $header .= "Organization: Test.org\r\n";
                            $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
                                                   
                            $message = "
                                    <b>Dear ".ucwords($username).",<br /><br />Thank you for registering on Test!</b><br /><b>Email : $email</b><br /><br />
                                    But before we can activate your account, one last step must be taken to complete your registration.
                                    Please note, you must complete this last step to become a registered member. You will only need to visit this URL once to activate your account.
                                    To complete your registration, please visit this URL:<br />
                                     After verification : <a href='$url'>Sign in</a><br />
                                    To sign up for our newsletter click <a href='$url/newsletter'>here</a><br /><br />
                                    <b>Best Regards,<br />
                                     Test Team</b>";

                        $res = wp_mail($to, $subject, $message, $headers);
                        $success = 1;
                        $user_id = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."users WHERE user_login = '$username' ",ARRAY_A);
                       
                        $secure_cookie = is_ssl() ? true : false;
                        wp_set_auth_cookie( $user_id['ID'], true, $secure_cookie );
                        //wp_safe_redirect(home_url());
                        ?>
                        <script>window.location.href='<?php echo home_url();?>';</script>
                        <script>
                            message('<?php echo json_encode($errors);?>');
                        </script>
                        <?php
           
                    }
                    else {
                        ?>
                            <script>
                                message('<?php echo json_encode($errors);?>');
                            </script>
                        <?php
                    }
           
                }

            }
        ?>
       
        <div class="signup-form">
                    <form method="post" action="#" id="RegisterForm">
                        <ul>
                            <li>
                                <input type="text" value="" class="text-bx" placeholder="Username" name="username" maxlength="20" autocomplete="off" />
                            </li>
                            <li>
                                <input type="email" value="" class="text-bx" placeholder="Email" name="email" maxlength="60" autocomplete="off" />
                            </li>
                            <li>
                                <input type="password" value="" class="text-bx" placeholder="Password" name="password" maxlength="30" autocomplete="off" />
                            </li>
                            <li>
                                <input type="checkbox" name="terms" id="terms" class="check" /><p>By creating your account you confirm that youve read
                                and accepted the <a href="#terms-content" class="fancybox accpt_te">Terms of Service.</a></p>
                                <input type="submit" name="signup" value="Sign-up for ePray" class="sgn-up" />
                            </li>
                        </ul>
                    </form>
                </div>
           
       
<?php
}
//add_shortcode('mk_registration', 'registrationForm');
registrationForm();
get_footer();
?>

3) Create backend page name "Register", Select template "Custom Register" and publish page.

How to create custom login page on frontend side in wordpress?

1) On index.php below get_header();

<?php
            if(!is_user_logged_in())
{
    ?>
    <script>window.location.href = '<?php echo home_url()."/login";?>';</script>
    <?php
    //wp_redirect(home_url()."/login");
}   
?>

2)Create file name "custom-login.php" and paste the following

<?php
/*
Template Name: Custom Login
*/
get_header();   
    if(isset($_POST["wp-submit"]))
    {
        $args = array(
        'echo' => true,
        'redirect' => site_url( $_SERVER['REQUEST_URI'] ),
        'form_id' => 'loginform',
        'label_username' => __( 'Username' ),
        'label_password' => __( 'Password' ),
        'label_remember' => __( 'Remember Me' ),
        'label_log_in' => __( 'Log In' ),
        'id_username' => 'user_login',
        'id_password' => 'user_pass',
        'id_remember' => 'rememberme',
        'id_submit' => 'wp-submit',
        'remember' => true,
        'value_username' => NULL,
        'value_remember' => false );
        $args = array('redirect' => get_permalink( get_page( $page_id_of_member_area ) ) );
    }
   
    if(is_user_logged_in())
    {
    ?>
        <script>window.location.href = '<?php echo home_url();?>';</script>
    <?php
    }
    else
    {
        wp_login_form( $args );
    }
get_footer();
?>

3) Create backend page name "Login", Select template "Custom Login" and publish page.

how to create custom post type with category in Wordpress?


function my_custom_post_product() {
  $args = array();
  register_post_type( 'product', $args );
}
add_action( 'init', 'my_custom_post_product' );

function my_custom_post_products() {
  $labels = array(
    'name'               => _x( 'Products', 'post type general name' ),
    'singular_name'      => _x( 'Product', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'book' ),
    'add_new_item'       => __( 'Add New Product' ),
    'edit_item'          => __( 'Edit Product' ),
    'new_item'           => __( 'New Product' ),
    'all_items'          => __( 'All Products' ),
    'view_item'          => __( 'View Product' ),
    'search_items'       => __( 'Search Products' ),
    'not_found'          => __( 'No products found' ),
    'not_found_in_trash' => __( 'No products found in the Trash' ),
    'parent_item_colon'  => '',
    'menu_name'          => 'Products'
  );
  $args = array(
    'labels'        => $labels,
    'description'   => 'Holds our products and product specific data',
    'public'        => true,
    'menu_position' => 5,
   'supports'      => array( 'title','author', 'editor','thumbnail','trackbacks' ,'excerpt','comments' ,'custom-fields','revisions','page-attributes','post-formats'),
    'has_archive'   => true,
  );
  register_post_type( 'product', $args );
}
add_action( 'init', 'my_custom_post_products' );


function my_updated_messages( $messages )
{
  global $post, $post_ID;
  $messages['product'] = array(
    0 => '',
    1 => sprintf( __('Product updated. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Product updated.'),
    5 => isset($_GET['revision']) ? sprintf( __('Product restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Product published. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Product saved.'),
    8 => sprintf( __('Product submitted. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Product scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview product</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Product draft updated. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
  );
  return $messages;
}
add_filter( 'post_updated_messages', 'my_updated_messages' );

function my_taxonomies_product()
{
// Hirarchical false = tags and true = categories
register_taxonomy("product_category", array("product"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Product", "rewrite" => true));
register_taxonomy("product_tags", array("product"), array("hierarchical" => false, "label" => "Tags", "singular_label" => "tags", "rewrite" => true));
}

add_action( 'init', 'my_taxonomies_product',0);

Wordpress create url with custom params and custom template

1) Place following on functions.php file

function add_rewrite_rules($aRules) {
    $aNewRules = array('newcustomtemplatepage/([^/]+)/?$' => 'index.php?pagename=newcustomtemplatepage&user=$matches[1]');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

2) Save paramalinks on backend side (Settings -> Permalinks -> Save Changes)

Wordpress custom photo gallery with custom post type


//----------------------------------------------
//--------------add theme support for thumbnails
//----------------------------------------------
if ( function_exists( 'add_theme_support')){
add_theme_support( 'post-thumbnails' );
}
add_image_size( 'admin-list-thumb', 80, 80, true); //admin thumbnail

//----------------------------------------------
//----------register and label gallery post type
//----------------------------------------------
$gallery_labels = array(
    'name' => _x('Gallery', 'post type general name'),
    'singular_name' => _x('Gallery', 'post type singular name'),
    'add_new' => _x('Add New', 'gallery'),
    'add_new_item' => __("Add New Gallery"),
    'edit_item' => __("Edit Gallery"),
    'new_item' => __("New Gallery"),
    'view_item' => __("View Gallery"),
    'search_items' => __("Search Gallery"),
    'not_found' =>  __('No galleries found'),
    'not_found_in_trash' => __('No galleries found in Trash'),
    'parent_item_colon' => ''
     
);
$gallery_args = array(
    'labels' => $gallery_labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'capability_type' => 'post',
    'supports' => array('title', 'excerpt', 'editor', 'thumbnail'),
    'menu_icon' => get_bloginfo('template_directory') . '/images/photo-album.png' //16x16 png if you want an icon
);
register_post_type('gallery', $gallery_args);


//----------------------------------------------
//------------------------create custom taxonomy
//----------------------------------------------
add_action( 'init', 'jss_create_gallery_taxonomies', 0);

function jss_create_gallery_taxonomies(){
    register_taxonomy(
        'phototype', 'gallery',
        array(
            'hierarchical'=> true,
            'label' => 'Photo Types',
            'singular_label' => 'Photo Type',
            'rewrite' => true
        )
    );  
}

//----------------------------------------------
//--------------------------admin custom columns
//----------------------------------------------
//admin_init
add_action('manage_posts_custom_column', 'jss_custom_columns');
add_filter('manage_edit-gallery_columns', 'jss_add_new_gallery_columns');

function jss_add_new_gallery_columns( $columns ){
    $columns = array(
        'cb'                =>        '<input type="checkbox">',
        'jss_post_thumb'    =>        'Thumbnail',
        'title'                =>        'Photo Title',
        'phototype'            =>        'Photo Type',
        'author'            =>        'Author',
        'date'                =>        'Date'
     
    );
    return $columns;
}

function jss_custom_columns( $column ){
    global $post;
 
    switch ($column) {
        case 'jss_post_thumb' : echo the_post_thumbnail('admin-list-thumb'); break;
        case 'description' : the_excerpt(); break;
        case 'phototype' : echo get_the_term_list( $post->ID, 'phototype', '', ', ',''); break;
    }
}

//add thumbnail images to column
add_filter('manage_posts_columns', 'jss_add_post_thumbnail_column', 5);
add_filter('manage_pages_columns', 'jss_add_post_thumbnail_column', 5);
add_filter('manage_custom_post_columns', 'jss_add_post_thumbnail_column', 5);

// Add the column
function jss_add_post_thumbnail_column($cols){
    $cols['jss_post_thumb'] = __('Thumbnail');
    return $cols;
}

function jss_display_post_thumbnail_column($col, $id){
  switch($col){
    case 'jss_post_thumb':
      if( function_exists('the_post_thumbnail') )
        echo the_post_thumbnail( 'admin-list-thumb' );
      else
        echo 'Not supported in this theme';
      break;
  }
}

How to implement ajax in wordpress?

index.php

1)
<a onclick="fnRequest()">Test Request</a>
<a id="response_text"></a>


2)
<script type="text/javascript">
function fnRequest()
{
    var data = {};
    data.register_email = "test";
    data.action = "request_action";
    jQuery.post('<?php echo rawurldecode(esc_url(home_url( '/'))); ?>wp-admin/admin-ajax.php',data, responsefunction);
}
function responsefunction(result)
{
    $("#response_text").html(result);
    //alert(result);
}
</script>


3)
functions.php

add_action('wp_ajax_request_action', 'request_action');
add_action('wp_ajax_nopriv_request_action' , 'request_action');
function request_action()
{
    echo "Testing response";
}