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.
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 |
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
Wordpress hooks for Adding scripts with it
Wordpress has built in Javascripts and few other built in functions like plupload, tinymce, swf, simplepie, thivkbox and jQuery. There also you can add your custom scripts into it. here i will guide you to add your custom script into your WordPress theme.
There are two possible sides to add your script.
1. Admin end or Back end
2. Front end
1. If you want add your custom script into wordpress admin page , you can add it in two areas. Header and footer sides.
Now if you want your script to run in header of your wordpress admin. just use this acction hook.
Before that save your custom script into a directory. than use this action script
add_action('admin_head', 'your script_function_name');
and also admin_footer for footer scripts.
2. Front end scripts.
use this action on you theme functions.php or your plugin file
add_action('wp-head', 'your function_name_here');
also front end footer scripts
add_action('wp_footer' , 'your_function_name_here');
thats it to add your custom scrips into WordPress
07:40 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.
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"
And hook your tiny with the help of jquery code. here it will help you to create responsive theme
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.
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 }
}
<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 Front End Multiple File Upload
While customizing Wordpress for our suitable cms solutions. We have certain things required from our customers. So it requires front end media upload. Even few things require to gather details and posts from users. If it requires you can also provide your user to upload media files from the front end of your site. May be of my following code can help you to create front end upload with multiple files simultaneously from single from .
You don't need to use any of the following things : flash ,js, jquery, and ajax . It works on all the browsers and simple HTML 5 codes and php code. This will work well on your old browsers like IE 6 . Also works well on your mobile devices.
create HTML form like this
<form action="upload.php" method="post" name="front_end_upload" >
<label> Attach all your files here :<input type="file" name="upload_attachments[]" multiple="multiple" > </label>
<input type="submit" name="Upload" >
</form>
The above HTML form handles the user upload files at your sites front-end. Now code for your back end to store the files.
//upload.php
if( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
if ( $_FILES ) {
$files = $_FILES["upload_attachments"];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array ("screenshots" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
}
}
}
The above code will handle the operation of getting files and send to your Wordpress function insert_attachment that we have added on your theme fiel "function.php" or your plugin's init action function.
here is the code for insert attachment function
################################################################################
// image Attachment
################################################################################
function insert_attachment($file_handler,$post_id,$set_thu=false) {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($set_thu) set_post_thumbnail($post_id, $attach_id);
return $attach_id;
}
that's it. to perform front end multiple file upload.
21:32 by Moviiee Thandura · 1
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
Create Custom Post Type and Custom Taxonomies in WordPress
Everyone's blog and site have some unique feature. So definitly we need customization of posts and its categories. The customization is depending upon our blog area. For eaxmple , Movie review sites, General articles, technical assistance, and etc. How do we create it based on our need and necessary?. Here i created a custom post type and custom taxonomy for movie review theme.
For creating Movie review we need a custom post type named as 'movie_review' and custom category named as 'movie_type'. And i will show you how to create and use it form them.
1. First create Custom post type by the following code.
register_post_type( 'movie_review', array(
'labels' => array(
'name' => 'Movie Review',
'singular_name' => 'Movie Review',
'add_new' => 'Add New',
'add_new_item' => 'Add New Movie Review',
'edit' => 'Edit',
'edit_item' => 'Edit Movie Review',
'new_item' => 'New Movie Review',
'view' => 'View',
'view_item' => 'View Movie Review',
'search_items' => 'Search Movie Reviews',
'not_found' => 'No Movie Reviews found',
'not_found_in_trash' =>
'No Movie Reviews found in Trash',
'parent' => 'Parent Movie Review'
),
'public' => true,
'menu_position' => 4,
'supports' => array( 'title', 'editor', 'comments', 'thumbnail','excerpt','custom-fields','comments'),
'taxonomies' => array( 'movie_type'), 'menu_icon' => get_bloginfo('template_url') . '/images/submit_pro.png','has_archive' => true )
);
here we created a custom post type namely 'movie review' and ready to add posts under movie review post. Look your admin Page below the Posts column it will apear.
2. Create custom Taxonomy. for creating custom taxonomies for custom posts, we need to know two of the taxonomy functions.
register_taxonony($taxonomy, $object_type, $args) ;
register_taxonomy_for_object_type($taxonomy, $object_type);
$taxonomy variable contains the information of our newly creating taxonomy name 'movie_type' and
$object_type represents our custom post type namely 'movie_review'.
Here is the full code for custom taxonomy
register_taxonomy( 'movie_type', array('movie_review'), array(
'hierarchical' => true, 'labels' => array(
'name' => __( 'Movie', 'mywptuts'),
'singular_name' => __( 'Movie Category', 'mywptuts'),
'search_items' => __( 'Search Movie', 'mywptuts'),
'all_items' => __( 'All Movie', 'mywptuts'),
'parent_item' => __( 'Parent Movie Category', 'mywptuts'),
'parent_item_colon' => __( 'Parent Movie Category:', 'mywptuts'),
'edit_item' => __( 'Edit Movie Category', 'mywptuts'),
'update_item' => __( 'Update Movie Category', 'mywptuts'),
'add_new_item' => __( 'Add New Movie Category', 'mywptuts'),
'new_item_name' => __( 'New Movie', 'mywptuts'),
'menu_name' => __( 'Movie' )
),
'show_ui' => true,
'query_var' => true,
'update_count_callback' => '_update_post_term_count',
'rewrite' => array( 'slug' =>'movie_type', 'hierarchical' => true ),
)
);
$movie_types = array(
'Action',
'Thriller',
'Horror',
'Comedy',
'historical'
);
if ($movie_types) foreach($movie_types as $movie_type) {
if (!get_term_by( 'slug', sanitize_title($movie_type), 'movie_type')) {
wp_insert_term($movie_type, 'movie_type');
}
}
And a single line of code can help you to avoid consequences of custom post type and custom taxonomy error.
register_taxonomy_for_object_type('movie_type','movie_review');
for avoid minetraps.
Thats it to create custom post type and taxonomies. If you have any idea and improvements drop a comment here.
03:41 by Unknown · 0
Subscribe to:
Posts (Atom)