PHP Developer

Thursday, 31 March 2016

WordPress Post Custom Pagination Without Plugin

WordPress Post Custom Pagination Without Plugin

This code helps you to create template and get post with pagination without using plugin.

<?php

/*

Template Name: Post Pagination without Plugin in WordPress

*/
get_header();
?>
<?php
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $wp_query->max_num_pages
) );
?>
<?php
function wp_pagination() {
global $wp_query;
$big = 12345678;
$page_format = paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $wp_query->max_num_pages,
    'type'  => 'array'
) );
if( is_array($page_format) ) {
            $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
            echo '<div><ul>';
            echo '<li><span>'. $paged . ' of ' . $wp_query->max_num_pages .'</span></li>';
            foreach ( $page_format as $page ) {
                    echo "<li>$page</li>";
            }
           echo '</ul></div>';
}
}
?>

<article id="core_middle_column" class="col-md-8 col-sm-8"><div id="core_ajax_callback"></div>
<div class="clearfix" id="recentlistings">
<?php 

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

query_posts(array( 'posts_per_page' => 2, 'post_type' => 'post', 'post_status' => 'publish', 'post__in' => array(1, 2, 3, 4), 'paged' => $paged ));

if ( have_posts() ) : ?>
<div class="_searchresultsdata">
<div class="panel panel-default">
<div class="list_style  wlt_search_results row">
<?php while ( have_posts() ) : the_post(); ?>
<div class="itemdata col-md-4 item-121 col-sm-6 col-xs-12">
<div class="thumbnail clearfix">
<?php echo get_the_title();?>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
</div>
<div class="custom_pagination"><?php wp_pagination(); ?></div>
<?php else : ?>
<?php // no posts found message goes here ?>
<?php endif; ?>
</div>
</article>
<style>
.custom_pagination ul {
  display: initial;
}

.custom_pagination li:first-child{
 background-color: #fff;
  border: 1px solid #ddd;
  color: #0b5b96;
  list-style: outside none none !important;
  padding: 6px 12px !important;
  text-decoration: none;
  border-radius:15px;
  float:right !important;
}

.custom_pagination li {
  float: left !important;
  list-style: outside none none !important;
}

.custom_pagination .page-numbers {
  background-color: #fff;
  border: 1px solid #ddd;
  color: #0b5b96;
 list-style: outside none none !important;
  padding: 6px 12px !important;
  text-decoration: none;
float: left;
}

.page-numbers.current {
  background-color: #0b5b96 !important;
  color: #fff !important;

}
</style>
<?php
get_footer();
?>

Monday, 28 March 2016

Add and Removes a Capability for a User Role in Wordpress

Add and Removes a Capability for a User Role in Wordpress

Add this code in function.php to Add and Removes a Capability from a User Role

<?php
/**
 * Remove capabilities from editors.
 *
 * Call the function when your plugin/theme is activated.
 */

function wpcodex_set_capabilities() {

    // Get the role object.
    $editor = get_role( 'editor' ); // Get alredy registerd Role "Editor" in wordpress

    // A list of capabilities to remove from editors.
    $caps_remove = array(
        'moderate_comments',
        'manage_categories',  // Allows user to manage post categories
        'manage_links',  // Allows user to edit links
        'edit_others_posts',  // Allows user to edit others posts not just their own
        'edit_others_pages',  // Allows user to edit pages
        'delete_posts',  //  Allows user to delete posts
        'edit_themes', // false denies this capability. User can’t edit your theme
        'install_plugins', // User cant add new plugins
        'update_plugin', // User can’t update any plugins
        'update_core', // user cant perform core updates
    );
   
    // A list of capabilities to Add for editors.
    $caps_add = array(
        'read', // true allows this capability
        'edit_posts', // Allows user to edit their own posts
        'edit_pages', // Allows user to edit pages
        'edit_others_posts', // Allows user to edit others posts not just their own
        'create_posts', // Allows user to create new posts
        'manage_categories', // Allows user to manage post categories
        'publish_posts', // Allows the user to publish, otherwise posts stays in draft mode
    );

    foreach ( $caps_remove as $cap ) {
        // Remove the capability.
        $editor->remove_cap( $cap );
    }
   
    foreach ( $caps_add as $capd ) {
        // Add the capability.
        $editor->add_cap( $capd );
    }
}
add_action( 'init', 'wpcodex_set_capabilities' );

?>

Create New User Role With Capability in Wordpress

Create New User Role With Capability in Wordpress


Add below code in function.php, then new role "Client" is registered with capabilities .

<?php
$result = add_role( 'client', __(

'Client' ),

array(

'read' => true, // true allows this capability
'edit_posts' => true, // Allows user to edit their own posts
'edit_pages' => true, // Allows user to edit pages
'edit_others_posts' => true, // Allows user to edit others posts not just their own
'create_posts' => true, // Allows user to create new posts
'manage_categories' => true, // Allows user to manage post categories
'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode
'edit_themes' => false, // false denies this capability. User can’t edit your theme
'install_plugins' => false, // User cant add new plugins
'update_plugin' => false, // User can’t update any plugins
'update_core' => false // user cant perform core updates

)

);

?>

Saturday, 27 February 2016

Custom Pagination Code For Wordpress, PHP with MySql

Custom Pagination Code For Wordpress, PHP with MySql


Pagination in php with custom query


<?php
/**
 * Template Name: Downloded Files Page
 *
 * @package WordPress
 * @subpackage Twenty_Fourteen
 * @since Twenty Fourteen 1.0
 */


get_header(); ?>
<?php
function paginate($reload, $page, $tpages) {
    $adjacents = 2;
    $prevlabel = "&lsaquo; Prev";
    $nextlabel = "Next &rsaquo;";
    $out = "";
    // previous
    if ($page == 1) {
        $out.= "<span>" . $prevlabel . "</span>\n";
    } elseif ($page == 2) {
        $out.= "<li><a  href=\"" . $reload . "\">" . $prevlabel . "</a>\n</li>";
    } else {
        $out.= "<li><a  href=\"" . $reload . "&amp;pageno=" . ($page - 1) . "\">" . $prevlabel . "</a>\n</li>";
    }
 
    $pmin = ($page > $adjacents) ? ($page - $adjacents) : 1;
    $pmax = ($page < ($tpages - $adjacents)) ? ($page + $adjacents) : $tpages;
    for ($i = $pmin; $i <= $pmax; $i++) {
        if ($i == $page) {
            $out.= "<li  class=\"active\"><a href=''>" . $i . "</a></li>\n";
        } elseif ($i == 1) {
            $out.= "<li><a  href=\"" . $reload . "\">" . $i . "</a>\n</li>";
        } else {
            $out.= "<li><a  href=\"" . $reload . "&amp;pageno=" . $i . "\">" . $i . "</a>\n</li>";
        }
    }
   
    if ($page < ($tpages - $adjacents)) {
        $out.= "<li><a style='font-size:11px' href=\"" . $reload . "&amp;pageno=" . $tpages . "\">" . $tpages . "</a>\n</li>";
    }
    // next
    if ($page < $tpages) {
        $out.= "<li><a  href=\"" . $reload . "&amp;pageno=" . ($page + 1) . "\">" . $nextlabel . "</a>\n</li>";
    } else {
        $out.= "<span style='font-size:11px'>" . $nextlabel . "</span>\n";
    }
    $out.= "";
    return $out;
}

$per_page = 2;         // number of results to show per page
$result = mysql_query("SELECT * FROM wp_uploads");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);//total pages we going to have

//-------------if page is setcheck------------------//
if (isset($_GET['pageno'])) {
    $show_page = $_GET['pageno'];             //it will telles the current page
    if ($show_page > 0 && $show_page <= $total_pages) {
        $start = ($show_page - 1) * $per_page;
        $end = $start + $per_page;
    } else {
        // error - show first set of results
        $start = 0;             
        $end = $per_page;
    }
} else {
    // if page isn't set, show first set of results
    $start = 0;
    $end = $per_page;
}
// display pagination
$page = intval($_GET['pageno']);

$tpages=$total_pages;
if ($page <= 0)
    $page = 1;
?>

<div id="main-content" class="main-content">
    <div class="container">
        <div id="primary" class="content-area">
            <div id="content" class="site-content" role="main">
                <div class="row">
                    <h2 class="upload_front_head">Uploaded File List</h2>
                    <div class="first_div" style="text-align:center;">
                        <div class="div_heading">
                            <!--<div class="heading_div">S.No.</div>-->
                            <div class="heading_div">Ttile</div>
                            <div class="heading_div">File Name</div>
                        </div>
                        <?php
                        $n= 0;
                        // loop through results of database query, displaying them in the table
                        for ($i = $start; $i < $end; $i++) {
                            $n = $n + 1;
                            // make sure that PHP doesn't try to show results that don't exist
                            if ($i == $total_results) {
                                break;
                            }
                         
                            // echo out the contents of each row into a table
                           
                            echo "<div class='content_row'>";
                                //echo "<div class='content_data'><strong>".$n.".<strong></div>";
                               
                                echo "<div class='content_data'>".mysql_result($result, $i, 'title')."</div>";
                               
                                echo "<div class='content_data'>".mysql_result($result, $i, 'origional_file')."</div>";
                               
                            echo "</div>";
                        } 
                        ?>

                    </div>
                   
                    <div class="pagination_section">
                        <?php
                        $reload = get_page_link() . "?tpages=" . $tpages;
                        echo '<div class="pagination"><ul>';
                        if ($total_pages > 1) {
                            echo paginate($reload, $show_page, $total_pages);
                        }
                        echo "</ul></div>";
                        // pagination
                        ?>
                    </div>
                </div>
            </div><!-- #content -->
        </div><!-- #primary -->
    </div>
</div><!-- #main-content -->
<style>
.pagination_section {
  float: left;
  margin-top: 10px;
  text-align: center;
  width: 100%;
}
.pagination {
  height: 40px;
  margin: 20px 0;
}
.pagination ul {
  border-radius: 3px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  display: inline-block;
  margin-bottom: 0;
  margin-left: 0;
}
.pagination ul li {
  display: inline;
}
.pagination li:first-child a, .pagination li:first-child span, .pagination li a {
  border-left-width: 1px;
  border-radius: 3px 0 0 3px;
  color: #3281ae;
  font-weight: 800;
}
.pagination a, .pagination span {
  -moz-border-bottom-colors: none;
  -moz-border-left-colors: none;
  -moz-border-right-colors: none;
  -moz-border-top-colors: none;
  background-color: #fff;
  border-color: #ddd;
  border-image: none;
  border-style: solid;
  border-width: 1px 1px 1px 0;
  float: left;
  line-height: 38px;
  padding: 0 14px;
  text-decoration: none;
}
.pagination .active a, .pagination .active span {
  color: #999;
  cursor: default;
}
.pagination a:hover, .pagination .active a, .pagination .active span {
  background-color: #f5f5f5;
}
</style>

<?php
get_footer();
?>

Monday, 1 February 2016

Create Shortcode to Show Bredcrum of Post or Page in Wordpress

 Create Shortcode to Show Bredcrum of Post or Page in Wordpress


This Code helps you to show Bredcrum or post and page where you want. And Shortcode is [page_bredcrum]

<?php
/************** Create Shortcode For Bredcrum START ****************/

function page_bredcrum_path() {
    $delimiter = '>';
  $currentBefore = '<span class="current">';
  $currentAfter = '</span>';
  if ( !is_home() && !is_front_page() || is_paged() ) {
    echo '<div id="crumbs">';
    echo '<a href="'.site_url().'">Home</a> '.$delimiter.' ';
    global $post;
    if ( is_page() && !$post->post_parent ) {
        echo $currentBefore;
        the_title();
        echo $currentAfter; }
    elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    }
    echo '</div>';
  }
}
add_shortcode('page_bredcrum', 'page_bredcrum_path');


/************** Create Shortcode For Bredcrum END ****************/
?>

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>";

?>