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

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

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