Namecheap.com - Cheap domain name registration, renewal and transfers - Free SSL Certificates - Web Hosting
Showing posts with label ideas. Show all posts
Showing posts with label ideas. Show all posts

Get 30 Individual Days Sales report from mysql - Wordpress


Now days so many eCommerce sites are coming with sophisticated features. Eventhough here i will give an easy way to get sales report or report for individual days. 

Here we are going to use a small php piece of php code with loop to get required individual day report. Its not only for the wordpress code. Also you can use for your own php site. 

Initially i thought to bring it as report data. but if we show it as a chart is ease of understand. so i make it with Simple chart namely  "Chart.js" You can also use it your own js or php chart for representation of data.

First of all we need a mysql table with your desired name. here i created a sample table for easy understanding.  

Note : Here i wrote Wordpress functions , if you want to use it for your php site, just add few lines of code by replacing built in wordpress functions. 
 
$sql_sales = "CREATE TABLE IF NOT EXISTS $kv_sales ( id mediumint(10) NOT NULL AUTO_INCREMENT, date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, pro_id mediumint(9), txn_id varchar(30), txn_type varchar(20), gateway varchar(30), buyer_email varchar(40), status varchar(20), payer_status varchar(20), pro_price float, parent_cur varchar(5), convert_cur varchar(5), convert_fee float, gross_amt float, fee_amt float, tax float, net_amt float, profit_amt float, UNIQUE KEY id (id) )ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;"; dbDelta($sql_sales); // you have to use mysql_query for php site users.
Than, I have insert some data's for using it for our sample report. We need to prepare monthly and weekly, even yearly report with this function. All you have to do is change the $period variable to get your desired period values.

  Next, You have to write SQL query for getting data between certain periods. Here I wrote code 

$sale_table_name = $wpdb->prefix.'sales_report' ;
$period= 30 ;  // Your required period for retrieve data.
$cur_stat= 'USD' ; 
for ( $i = $period; $i>=0; $i-- ) {
$gross_amt_day = 0;
$net_amt_day  = 0;
$profit_amt =0 ; 
$r_date = 0 ;
$selected_results = $wpdb->get_results("SELECT gross_amt, net_amt, profit_amt , DATE_FORMAT(`date`,'%e %b')AS date FROM $sale_table_name WHERE DATE(date) = DATE_SUB( CURDATE( ) ,INTERVAL '$i' DAY ) AND parent_cur = '$cur_stat'");
//echo count($selected_results) . '-';
foreach($selected_results as $result) {
$r_date = $result->date ;
$gross_amt_day += $result->gross_amt;
$net_amt_day += $result->net_amt ; 
$profit_amt += $result->profit_amt ; 
}
$res_date[] = $r_date ; 
$gross_amt_ar[] = $gross_amt_day ; 
$net_amt_ar[] = $net_amt_day ;
$profit_amt_ar[] = $profit_amt;
}
}
The following code helps to retrieve the data between two periods. Through the sql code by giving  your necessary time period you will get your desired result.

SELECT gross_amt, net_amt, profit_amt , DATE_FORMAT(`date`,'%e %b')AS date FROM $sale_table_name WHERE DATE(date) = DATE_SUB( CURDATE( ) ,INTERVAL '$i' DAY ) AND parent_cur = '$cur_stat'   

Though i wrote all the code into a file you want it download from Github

07:15 by Moviiee Thandura · 3

Working with WordPress Custom Hooks


WordPress Action Hooks
Every developer must know about wordpress hooks . Its classified as two area based on its usage and necessity. here it is

  1. Action hooks and
  2. Filter hooks.

Both are doing much quite similar jobs but having small differences.

First of all we must know what is action hooks and how it is organised with wordpress.?
  
Its not just a simple thing behind your wordpress CMS. Its works more with database tables, template files , custom codes of plugin and themes.  

So each and every action are performed through the code and functions.  for every functions have certain priority and time to perform its operations. so it's all hooked with this functions .

now we can use its built in hooks or else we can code it for our own. as always we know wordpress is blend like a shapeless objects. so you can blend its features based on your needs. 

you can find the list of wordpress hooks from wordpress codex. 

Also you can create a new one for your custom usage. 
 creation of custom hooks need the following steps. 

1. create your code with a your desired function name .

2. add your function with wordpress action hooks like the following line


  add_action('custom_hook_name', 'your_custom_function_name'); 


the above code hook your function with wordpress. 

3. than write your custom hook's function where you want to use it on your wordpress cms. 

The following code help you create your custom hooks function. 


   function custom_hook_name() {
         do_action('custom_hook_name');
   }
 
Thats it for emerging of your wordpress custom hooks for your custom operation. Any comments and feedback requested from you reader. 

05:44 by Unknown · 0

Create Responsive Menu With the Help of TinyNav,js - Wordpress


Now-a-days Responsive web designs and developments are so familiar, because of  different screens with different screen size and resolutions. There are plenty of web designs available to use responsive web designs. Here i will give very small code to create responsive menu for your WordPress Website.

First of all download TinyNav.js from its Original Site or from github.

And make our theme folder and add your downloaded script into it. Then enqueue Your script into WordPress by the following code. Add it on your Theme "functions.php"

wp_enqueue_script('tinynav' , get_template_directory_uri() . '/js/tinynav.min.js' , array('jquery'));

and create your menu through your wordpress admin menu settings or else through code. and you have to make the menu inside a id name #topnav . Here is a sample code your source view of web page.



<ul id="topnav">
  <li class="selected"><a href="/">Home</a></li>
  <li><a href="/about/">About</a></li>
  <li><a href="/contact/">Contact</a></li>
</ul>



and your add a small code to sleep tinynav while your site is on big screens. It must be used for small screens  screen resolution is less than 600 px. and add this to your theme  "style.css"

/* styles for desktop */
.tinynav { display: none }

/* styles for mobile */
@media screen and (max-width: 600px) {
    .tinynav { display: block }
    #nav { display: none }
}
And hook your tiny with the help of jquery code. here it will help you to create responsive theme


<script>
  $(function () {
    $("#nav").tinyNav();
  });
</script>

Thats it you have done all necessary works to add tinynav.js. And Now check your website by using different screen size. Use screenfly or some other tools to may the changes giving effect or not.





08:59 by Unknown · 3

WordPress - Hide Actual Download Url



WordPress customized many way .But when a user download your file from your blog. It happen to appear link like this " www.Yourwebsite.com/wp-content/uploads/2013/06/download.zip" It's showing the url link to your visitors where your file is located. Its giving security problem to your blog. You have to hide the actual url of your files location.

I tried to use a method to hide the download location and allow all downloads from the url like this  "www.yoursite.com/download/?m=d4wef4vbsdfv4334v45g6hg4rbvwq4vv.zip"

otherwise like this "www.yoursite.com/downloads/"

This is most secure because no one is going to know your file location. First thing we need to create a file namely "download.php" and link  it your wordpress theme file or plugin file.

go to your admin panel and under that pages and Add New then crreate page namely download and make sure the url look like above said one. Then add it to your download page  

['donload_page']

we have to send a file name or post id to downloads.php and make it downloadable by your user. So here i will use post id to make download.

Goto your download.php file and paste the following code in it.


<?php 

ob_start();
function download_link_page(){
    global $wpdb , $current_user , $wp_roles;
    get_currentuserinfo();
    $setting = wp_upload_dir();
    $allowed_referred = "";
    $base_dir = $setting['basedir'];
    $log_downloads = true;
    $down_stat_table = $wpdb->prefix.'download_stat';

    if(!empty($settings)) {
        foreach($settings as $setting) {
            if(rtrim($setting->allowed_referred) != "")
                $allowed_referred =  $setting->allowed_referred;
           
            if(rtrim($setting->base_dir) != "")
                $base_dir =  $setting->base_dir;

            if($setting->log_downloads == "0")
                $base_dir =  false;
        }
    }    

    define('ALLOWED_REFERRER', $allowed_referred);
    define('BASE_DIR',$base_dir);
    define('LOG_DOWNLOADS',$log_downloads);   
    define('LOG_FILE','downloads.log');

    $allowed_ext = array (
        'zip' => 'application/zip',
        'txt' => 'application/txt',
        'doc' => 'application/msword'   
    );   //Specify your support mine type for user download
    ####################################################################
    ###  DO NOT CHANGE BELOW
    ####################################################################
    if (ALLOWED_REFERRER !== '' && (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)) {
        if(strtoupper($_SERVER['HTTP_REFERER']) != home_url())  {
            $referredBy = strtoupper($_SERVER['HTTP_REFERER']);
            $parent   = strtoupper(home_url());
            $pos = strpos($referredBy, $parent);
            if ($pos === false) 
                die("Internal server error. Please contact system administrator.");
             else {     }
        }
    }
    set_time_limit(0);
    
    if (isset($_POST['item_number']) || (!empty($_POST['item_number']))) {
if (strpos($_POST['item_number'], "\0") !== FALSE) die('');
$post_id= trim($_POST['item_number']);
$args = array(
'post_type'   => 'attachment',
'numberposts' => -1,
'post_parent' => $post_id,
'post_mime_type' => 'application'
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ){
$fname = get_post_meta($attachment->ID,'_wp_attached_file',true);
$fname = substr($fname, 8); 
}
}
_e("Your download starts within five seconds.");

}else {

    _e("Sorry No File is specified to download.");
echo '</section>';
get_footer();
exit(0);
}
 if (!isset($_POST['txn_id']) || empty($_POST['txn_id'])) {
$gateway = "Free Gateway" ;
$txn_id = $post_id."_".$current_user->ID;
}
  else {
$txn_id = trim($_POST['txn_id']);
$gateway = trim($_POST['custom']);
}
    function find_file ($dirname, $fname, &$file_path) {        
        $dir = opendir($dirname);        
        while ($file = readdir($dir)) {
            if (empty($file_path) && $file != '.' && $file != '..') {
                if (is_dir($dirname.'/'.$file))
                    find_file($dirname.'/'.$file, $fname, $file_path);                
            else {
                if (file_exists($dirname.'/'.$fname)) {
                    $file_path = $dirname.'/'.$fname;
                    return;
                  }
            }
            }
        }

    } // find_file
    // get full file path (including subfolders)
    $file_path = '';
    find_file(BASE_DIR, $fname, $file_path);
    echo $file_path;
$fname ; 
    if (!is_file($file_path)) _e("File does not exist. Make sure you specified correct file name.");    

    $fsize = filesize($file_path); 
    $fext = strtolower(substr(strrchr($fname,"."),1));
    if (!array_key_exists($fext, $allowed_ext))  _e("Not allowed file type.");     

    if ($allowed_ext[$fext] == '') {
        $mtype = '';       
        if (function_exists('mime_content_type') && is_file($file_path) ) {
            $mtype = mime_content_type($file_path);
        }
        else if (function_exists('finfo_file') && is_file($file_path) ) {
            $finfo = finfo_open(FILEINFO_MIME); // return mime type
            $mtype = finfo_file($finfo, $file_path);
            finfo_close($finfo);  
        }
        if ($mtype == '') {
            $mtype = "application/force-download"; 
        }
    }
    else    $mtype = $allowed_ext[$fext];

    if (!isset($_GET['fc']) || empty($_GET['fc'])) {
        $asfname = $fname;
    }
    else {
        $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
        if ($asfname === '') $asfname = 'NoName';
    }
    $date =date('Y-m-d H:i:s');   
    $wpdb->insert($down_stat_table , array(
'time' => $date,
'project_id' => $post_id,
'buyer_name' => $current_user->user_login,
'buyer_email' => $current_user->user_email,
'txn_id' => $txn_id,
'gateway' => $gateway,
'ip_addr' => $_SERVER["REMOTE_ADDR"]
));
if( $gateway == 'Free Gateway' ) {
$down_count = get_post_meta($post_id, 'down_count', true);
$down_count = $down_count + 1;
update_post_meta($post_id, 'down_count', $down_count); 
}
$tot_charge = get_post_meta($post_id , 'total_charges', true);
$tot_charge = $tot_charge + $down_count * 1.25;
update_post_meta($post_id, 'total_charges' , $tot_charge);

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Type: $mtype");
    header("Content-Disposition: attachment; filename=\"$asfname\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $fsize);
ob_clean();   // discard any data in the output buffer (if possible)
flush();      // flush headers (if possible)

//readfile($file_path);
//exit();
//@readfile($file_path);

    $file = @fopen($file_path,"rb");
    if ($file) {
        while(!feof($file)) {
            print(fread($file, 1024*8));
            flush();
            if (connection_status()!=0) {
            @fclose($file);
            die();
        }
    }
    @fclose($file);
    }
    // log downloads
    if (!LOG_DOWNLOADS) die();

    $f = @fopen(LOG_FILE, 'a+');
    if ($f) {
        @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\n");
        @fclose($f);
    }    
}    add_shortcode( 'download_page', 'download_link_page' ); ?>


The above code can help you to create a secure download and hide your actual file location .Here we need to send post id to create download. So create form like this into your loop.php or single .php

<form method="post" action="<?php echo site_url('download'); ?>" >
<input type="hidden" name="item_number" value="<?php echo $post->ID; ?>" >
<input type="submit" value="Download" class="class-btn" name="submit"> 
</form> 

That's all  to create secured download manager for your files. Leave a comment here as your views of suggestions and feedbacks.

04:46 by Unknown · 4

WordPress Use Chart in Front and Back End Using Chart.js



Charts are so useful now a days, showing charts instead of data table , looks easy and ease of presence. There are so many Chart plugins are available to use. But that  are all not opt to your wordpress blog. So I found a way to use it on my own customization. First of all I tried to use php class for Drawing Charts but. None of that is free and looks nice. So i used Charts.js for drawing charts. It's light weight and create a animated view for drawing chart on your browser.

First you need Chart.min.js is need to use it. It is flexible to customize and it supports 6 types of charts. 

Additionally, excanvas.compiled js package is needed.  download it from Charts.js source site

first of all  enqueue these two files into wordpress, both in admin and front end use.


// Add IE Fallback for HTML5 and canvas
// - - - - - - - - - - - - - - - - - - - - - - -
function wp_charts_html5_support () {
    echo '<!--[if lt IE 8]>'; //this is for the support of HTML 5 which helps to draw chart  
    echo '<script src="'.plugins_url( '/js/excanvas.compiled.js', __FILE__ ).'"</script>';
    echo '<![endif]-->';
    echo ' <style>
    /*wp_charts_js responsive canvas CSS override*/
    .wp_charts_canvas {
    width:100%!important;
    max-width:100%;
    height:auto!important;
    }
    </style>';
}

// Register both  Scripts 
// - - - - - - - - - - - - - - - - - - - - - - -
function wp_charts_load_scripts() {

if ( !is_Admin() ) {
wp_register_script( 'charts-js', plugins_url('/js/Chart.min.js', __FILE__) );
wp_enqueue_script( 'charts-js' );
}
}
add_action( "wp_enqueue_scripts", "wp_charts_load_scripts" );
add_action('wp_head', 'wp_charts_html5_support');


here html support is used under wp_head to initiate the js function

 You can use color conversion and  showing of different color variations from this code

// make sure there are the right number of colours in the colour array
// - - - - - - - - - - - - - - - - - - - - - - -
if ( !function_exists('wp_charts_compare_fill') ) {
function wp_charts_compare_fill(&$measure,&$fill) {
// only if the two arrays don't hold the same number of elements
if (count($measure) != count($fill)) {
   // handle if $fill is less than $measure
   while (count($fill) < count($measure) ) {
       $fill = array_merge( $fill, array_values($fill) );
   }
   // handle if $fill has more than $measure
   $fill = array_slice($fill, 0, count($measure));
}
}
}

// color conversion function
// - - - - - - - - - - - - - - - - - - - - - - -
if (!function_exists( "wp_charts_hex2rgb" )) {
function wp_charts_hex2rgb($hex) {
  $hex = str_replace("#", "", $hex);

  if(strlen($hex) == 3) {
     $r = hexdec(substr($hex,0,1).substr($hex,0,1));
     $g = hexdec(substr($hex,1,1).substr($hex,1,1));
     $b = hexdec(substr($hex,2,1).substr($hex,2,1));
  } else {
     $r = hexdec(substr($hex,0,2));
     $g = hexdec(substr($hex,2,2));
     $b = hexdec(substr($hex,4,2));
  }

  $rgb = array($r, $g, $b);
  return implode(",", $rgb); // returns the rgb values separated by commas
}
}


data trailing function for serialize your data 

if (!function_exists('wp_charts_trailing_comma')) {
function wp_charts_trailing_comma($incrementor, $count, &$subject) {
$stopper = $count - 1;
if ($incrementor !== $stopper) {
return $subject .= ',';
}
}
}

Here we ready to draw a chart. We almost done except the function to give raw data for drawing a chart.  We have to give the parameters of the chart, i.e values to draw a chart .  Which type of chart we are going to use here. I already specified that chart.js supports 6 types of charts.
For example I use Pie Chart here.

array(
'type'             => 'pie',  //type of chart we are going to use
'title'            => 'chart',
'canvaswidth'      => '625',
'canvasheight'     => '625',
'width' => '48%',
'height' => 'auto',
'margin' => '5px',
'align'            => '',
'class' => '',
'labels'           => '',
'data'             => '30,50,10', //data for drawing a chart
'datasets'         => '30,50,100 next 20,90,75',   
'colors'           => '69D2E7,#E0E4CC,#F38630,#96CE7F,#CEBC17,#CE4264',
'fillopacity'      => '0.7',
'pointstrokecolor' => '#FFFFFF' );

 The above array contains a list of parameters for the chart. 


// Chart Shortcode 1
// - - - - - - - - - - - - - - - - - - - - - - -
function wp_charts_shortcode( $atts ) {

// Default Attributes
// - - - - - - - - - - - - - - - - - - - - - - -
extract( shortcode_atts(
array(
'type'             => 'pie',
'title'            => 'chart',
'canvaswidth'      => '625',
'canvasheight'     => '625',
'width'   => '48%',
'height'   => 'auto',
'margin'   => '5px',
'align'            => '',
'class'   => '',
'labels'           => '',
'data'             => '30,50,10',
'datasets'         => '30,50,100 next 20,90,75',
'colors'           => '69D2E7,#E0E4CC,#F38630,#96CE7F,#CEBC17,#CE4264',
'fillopacity'      => '0.7',
'pointstrokecolor' => '#FFFFFF'
), $atts )
);

// prepare data
$title    = str_replace(' ', '', $title);
$data     = explode(',', str_replace(' ', '', $data));
$datasets = explode("next", str_replace(' ', '', $datasets));
$colors   = explode(',', str_replace(' ','',$colors));
(strpos($type, 'lar') !== false ) ? $type = 'PolarArea' : $type = ucwords($type) ;

// output - covers Pie, Doughnut, and PolarArea
$currentchart = '<div class="'.$align.' '.$class.'" style="width:'.$width.';height:'.$height.';margin:'.$margin.';">';
$currentchart .= '<canvas id="'.$title.'" height="'.$canvasheight.'" width="'.$canvaswidth.'" class="wp_charts_canvas"></canvas></div>
<script>';

// start the js arrays correctly depending on type
if ($type == 'Line' || $type == 'Radar' || $type == 'Bar') {

wp_charts_compare_fill($datasets, $colors);
$total    = count($datasets);

// output labels
$currentchart .= 'var '.$title.'Data = {';
// if ( count($labels) > 0 ) {

$currentchart .= 'labels : [';
$labelstrings = explode(',',$labels);
// wp_charts_compare_fill($datasets, $labelstrings);
for ($j = 0; $j < count($labelstrings); $j++ ) {
$currentchart .= '"'.$labelstrings[$j].'"';
wp_charts_trailing_comma($j, count($labelstrings), $currentchart);
}
$currentchart .= '],';
// }

$currentchart .= 'datasets : [';
} else {
wp_charts_compare_fill($data, $colors);
$total = count($data);

$currentchart .= 'var '.$title.'Data = [';
}
// create the javascript array of data and attr correctly depending on type
for ($i = 0; $i < $total; $i++) {

if ($type === 'Pie' || $type === 'Doughnut' || $type === 'PolarArea') {

$currentchart .= '{
value : '. $data[$i] .',
color : '.'"'. $colors[$i].'"'.'
}';

} else if ($type === 'Bar') {

$currentchart .= '{
fillColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .','.$fillopacity.')",
strokeColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .',1)",
data : ['.$datasets[$i].']
}';

} else if ($type === 'Line' || $type === 'Radar') {

$currentchart .= '{
fillColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .','.$fillopacity.')",
strokeColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .',1)",
pointColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .',1)",
pointStrokeColor : "'.$pointstrokecolor.'",
data : ['.$datasets[$i].']
}';

}  // end type conditional
wp_charts_trailing_comma($i, $total, $currentchart);
}
// end the js arrays correctly depending on type
if ($type == 'Line' || $type == 'Radar' || $type == 'Bar') {
$currentchart .= ']
};';
} else {
$currentchart .= '];';
}
$currentchart .='var wpChart'.$title.$type.' = new Chart(document.getElementById("'.$title.'").getContext("2d")).'.$type.'('.$title.'Data);
</script>';
// return the final result
return $currentchart;
}

give parameter through $atts and draw your chart. if you have questions comment below.

03:20 by Unknown · 2

Namecheap.com - Cheap domain name registration, renewal and transfers - Free SSL Certificates - Web Hosting