Monday, May 18, 2015


How to create custom (Taxonomy) Category for custom post in WordPress

To create custom taxonomy (category) for the custom post type
Final code is  you need to add in the  function.php
Is  here 

add_action( 'init', 'create_book_tax' );

function create_book_tax() {
                register_taxonomy(
                                'photo',    // it is category type
                                'my_photo',
                                array(
                                                'label' => __( 'Competitions' ) ,  // category label
                                                'rewrite' => array( 'slug' => 'Competitions' ), 
                                                'hierarchical' => true,
                                )
                );
}


Thursday, May 14, 2015

How to create webservices in PHP tutorial


Here  I am showing one example of creating  the webservices  in php

First  you need to download the  soap library   to create the  webservies  on the server
You can download it from the link  http://sourceforge.net/projects/nusoap/
After that  you need to create  server.php file on you server
Server.php



<?php
//call library
require_once ('lib/nusoap.php');   // include the soap liberary here  

function getProd($category) {
    if ($category == "movies") {    //  here I am checking the  coming value from category is movies or not
        return join(",", array(
            "The is webservices test",
            " Writing  webservice  I am here ",
            "Build dynamic website with me"));          //  if  category is movies  then it will send this result to  your server
    }
    else {
            return "No products listed under that category";   // if there is other category then movies it will show this message
    }
}
 $server = new soap_server();
$server->register("getProd");
$server->service($HTTP_RAW_POST_DATA);

?> 



Need to create the files  newservice.php



<?php /* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

                /* soak in the passed variable or set our own */
                $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
                $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
                $user_id = intval($_GET['user']); //no default

                /* connect to the db */
                $link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
                mysql_select_db('database name,$link) or die('Cannot select the DB');

                /* grab the posts from the db */
                $query = "SELECT post_title, guid FROM table  WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
                $result = mysql_query($query,$link) or die('Errant query:  '.$query);

                /* create one master array of the records */
                $posts = array();
                if(mysql_num_rows($result)) {
                                while($post = mysql_fetch_assoc($result)) {
                                                $posts[] = array('post'=>$post);
                                }
                }

                /* output in necessary format */
                if($format == 'json') {
                                header('Content-type: application/json');
                                echo json_encode(array('posts'=>$posts));
                }
                else {
                                header('Content-type: text/xml');
                                echo '<posts>';
                                foreach($posts as $index => $post) {
                                                if(is_array($post)) {
                                                                foreach($post as $key => $value) {
                                                                                echo '<',$key,'>';
                                                                                if(is_array($value)) {
                                                                                                foreach($value as $tag => $val) {
                                                                                                                echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
                                                                                                }
                                                                                }
                                                                                echo '</',$key,'>';
                                                                }
                                                }
                                }
                                echo '</posts>';
                }

                /* disconnect from the db */
                @mysql_close($link);
}
?>




Now we need to create file   client.php

if(isset($_REQUEST['get_data']))
  {
   
$userid = $_REQUEST['userid'];
$count  = $_REQUEST['count'];

$url = “Api file path/newservice.php?user=$userid&num=$count&format=json";           

$client = curl_init($url);  
                 
                curl_setopt($client,CURLOPT_RETURNTRANSFER,1);
// get responce
$response = curl_exec($client);               
// decode
//echo "<pre>";
//print_r($response);
$result = json_decode($response);         //  to decode the json result   
//echo "<pre>";
//print_r($result);
}




<form method="post">
    User ID <input type="text" name="userid" value="">
                Number <input type="text" name="count" >
                <input type="submit" name="get_data" value="Get Data">
</form>



 Incoming results will show here   on your file .

foreach($result as $rr)
   {
  
   foreach($rr as $kk)
    {

       echo $kk->post->post_title."<br/>";
                                 //echo $k;
                                // echo $rr;
                                //echo "<pre>";
                                //print_r($kk);
                               
                                 //echo $rr[$k]->post->post_title ."<br/>";
                 }
   

  }

Ajax Jquery Tutorial Example

Jquery Ajax  Tutorial
For the  jquery ajax you  need to add the jquery library  first

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>


After that   you can write  the code for  ajax  by which you can get the  data from other file on server without refreshing
<script>
$.ajax({
  method: "POST",   //  ajax posting method
  url: " ‘your file path’ /ajax.php",   // File path and name on your server 
  data: { name: "vikas gautam ", location: "Mohali" }  // variable to pass to the  file ajax.php

})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );  // alert back response data  for the
  $(“# result”).html(msg);   // to pass the result to you htm div
  variable
  });

</script>

<div id=”result”></div>  /here the result will show









Wednesday, May 13, 2015

How to create custom post type in WordPress

 You can create  custom post type by the  simple wordpress  action   hook  just write a action hook

add_action( 'init', 'create_post_type' );

Now you need to write the  function 

function create_post_type() {
  your register post type code here
}

Now in the  function you need to add the  register post type and name   and view permission

  register_post_type( 'mycustom_blog',
    array(
      'labels' => array(
        'name' => __( 'My Blogs' ),
        'singular_name' => __( 'My Blog' )
      ),
      'public' => true,
      'has_archive' => true,
    )

Here  'mycustom_blog ‘ is the  custom post type and  which will save in database to difference the post type .
In the 'labels'  name  of the label which will show in the  backend .
Final code is  you need to add in the  function.php
Is  here

<?php
add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'mycustom_blog',
    array(
      'labels' => array(
        'name' => __( 'My Blogs' ),
        'singular_name' => __( 'My Blog' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );


} ?>

Plugin to get user visit time after login on the site

Here is the plug-in code which you can user to get the  user visit info on site  and how much time user  remain on site and logout .
You will get all the info in the admin panel with user’s field

<?php
/**
 * Plugin Name: User  Login logout  info
 * plugin URI: http://vikasbruce.blogspot.in/
 * Description:description here
 * Author: Vikas Gautam
 */
add_action('wp_login','vikas_last_login_time');
function vikas_last_login_time($login) {
    global $user_ID;
    $user = get_user_by('login', $login);
    $time_start = time();
                echo date_default_timezone_get();
                //date_default_timezone_set("Asia/Kolkata");
    $start_date = date("Y-m-d h:i:s");
    update_user_meta($user->ID, 'start_time', $time_start);
                update_user_meta($user->ID, 'start_date', $start_date);
}

add_action('wp_logout', 'vikas_time_on_logout');
function vikas_time_on_logout($user_id) {
    global $user_ID;
    $user = get_user_by('id', $user_ID);
               
                echo date_default_timezone_get();
                //date_default_timezone_set("Asia/Kolkata");
    $end_date = date("Y-m-d h:i:s");
                update_user_meta($user->ID, 'end_date', $end_date);
               
    $time_end = time();
    $time_start = get_user_meta($user->ID, 'start_time', true);
    $total_time = (intval($time_end) - intval($time_start));
    $total_time = round($total_time/60);
    $total_all_time = get_user_meta($user->ID, 'total_time', true);
    $total_time = $total_all_time + $total_time;
    update_user_meta($user->ID, 'total_time', $total_time);


    $logged_in_amount = get_user_meta($user->ID, 'logged_in_amount', true);
    $logged_in_amount = $logged_in_amount + 1;
    update_user_meta($user->ID, 'logged_in_amount', $logged_in_amount);

    $average_time = ($total_time/$logged_in_amount);
    update_user_meta($user->ID, 'average_time', $average_time);
}

add_filter('manage_users_columns', 'vikas_user_minutes_column');
function vikas_user_minutes_column($columns) {
    $columns['total_time'] = 'Total Time in  Minutes';
    $columns['logged_in_amount'] = 'Total time of Logins';
    $columns['average_time'] = 'Ave. Time Min./Login';
               
                $columns['start_date'] = 'Start Date';
                $columns['end_date'] = 'End date';
                 
    return $columns;
}

add_action('manage_users_custom_column',  'vikas_user_minutes_column_content', 10, 3);
function vikas_user_minutes_column_content($value, $column_name, $user_id) {
    $output = " ";
    $user = get_userdata( $user_id );
    if ( 'total_time' == $column_name )
        $output .= ($user->total_time);
    if ( 'logged_in_amount' == $column_name )
        $output .= ($user->logged_in_amount);
    if ( 'average_time' == $column_name )
        $output .= ($user->average_time);
                               
                if('start_date' == $column_name)
       $output .=($user->start_date);         
                if('end_date' == $column_name)
       $output .=($user->end_date);
                  
    return $output;
}

add_action('admin_footer', 'vikas__custom_user_buttons');
function vikas__custom_user_buttons() {
    $screen = get_current_screen();
    if ( $screen->id != "users" )   // Only add to users.php page
        return;
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('<option>').val('del_user_meta').text('Delete User Logs').appendTo("select[name='action']");
            $('<option>').val('export_user_meta').text('Export User Logs').appendTo("select[name='action']");
        });
    </script>
    <?php
}

add_action('load-users.php', 'vikas_delete_users_info');
function vikas_delete_users_info() {
    if(isset($_GET['action']) && $_GET['action'] === 'del_user_meta') {  // Check if our custom action was selected
        $del_users = $_GET['users'];  // Get array of user id's which were selected for meta deletion
        if ($del_users) {  // If any users were selected
            foreach ($del_users as $del_user) {
            delete_user_meta($del_user, 'logged_in_amount');
            delete_user_meta($del_user, 'total_time');
            delete_user_meta($del_user, 'average_time');
                                    delete_user_meta($del_user, 'start_date');
                                    delete_user_meta($del_user, 'end_date');
            }
        }
    }
}
?>

Export Mysql table records to the to csv file useing php

To export the sql table data to csv file

Below code you can user to expert and sql table data to the  csv file.

<?php 
$table = 'wp_users';  // table name here
$filename = tempnam(sys_get_temp_dir(), "csv");

$conn = mysql_connect("localhost", "root", "");    // data base connection crediential here
mysql_select_db("database",$conn);   // connect with the my sql database

$file = fopen($filename,"w");

// Write column names
$result = mysql_query("show columns from $table ",$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $colArray[$i] = mysql_fetch_assoc($result);
    $fieldArray[$i] = $colArray[$i]['Field'];
}
fputcsv($file,$fieldArray);

// Write data rows
$result = mysql_query("select * from $table",$conn);
for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $dataArray[$i] = mysql_fetch_assoc($result);
}
foreach ($dataArray as $line) {
    fputcsv($file,$line);
}

fclose($file);

header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=user_details.csv");

// send file to browser
readfile($filename);
unlink($filename);

?>