Thursday 21 April 2016

jquery Star rating plugin with php

 jquery Star rating plugin with php



 <script src="https://code.jquery.com/jquery-2.2.3.js"></script>
 <script type="application/javascript">
 $(document).ready(function(e) {
   $.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

$(function() {
    $('span.stars').stars();
});
});
 </script>



 <style>
  span.stars, span.stars span {
    display: block;
    background: url(images/stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

span.stars span {
    background-position: 0 0;
}
</style>

<!--  You can get avarage rating using php query get here where 3.5 -->

 <span class="stars">3.5</span>
 use this image for start rating
 https://drive.google.com/file/d/0BwNaFGxzigBud25jaG1XaWlfU0k/view?usp=sharing

Saturday 16 April 2016

Create Multiple Images Upload using Custom field or Meta box in Wordpress

Create Multiple Images Upload using Custom field or Meta box in Wordpress

<?php
/**
 * Plugin Name:       My Gallery
 */

add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );

function smashing_post_meta_boxes_setup(){
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
}

function smashing_add_post_meta_boxes(){
add_meta_box(
    'smashing-post-class',      // Unique ID
    esc_html__( 'Post Class', 'example' ),    // Title
    'smashing_post_class_meta_box',   // Callback function
    'post',         // Admin page (or post type)
    'normal',         // Context
    'default'         // Priority
  );
}


function smashing_post_class_meta_box($object){ ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>

 
  <p>
  </br>
  <label for="smashing-post-class"><?php _e( "Upload Your Image", 'example' ); ?></label>
  </br>
  <input type="file" id="wp_custom_attachment" name="wp_custom_attachment[]" multiple="multiple" size="25" />
  <br />
  <?php $imgs= get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

  $images=1;
$imgs=json_decode(base64_decode($imgs));
  if(count($imgs)>0){

  foreach ($imgs as $img){
   ?>

      <img src="<?php echo  $img; ?>" width="100px" height="100px"  />
      <?php if($images %4 ==0){ echo "<br>"; } ?>
    
    
<?php  $images++;} }
   ?>
  <input type="hidden" value="<?php echo base64_encode(json_encode($imgs)); ?>" name="save_images"/>
  </p>
  <?php
}


function smashing_save_post_class_meta( $post_id, $post ) {

if ( ! function_exists( 'wp_handle_upload' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

  /* Verify the nonce before proceeding. */
  if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
    return $post_id;

  /* Get the post type object. */
  $post_type = get_post_type_object( $post->post_type );

  /* Check if the current user has permission to edit the post. */
  if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
    return $post_id;

  /* Get the posted data and sanitize it for use as an HTML class. */
  $new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );


if(!empty($_FILES['wp_custom_attachment']['name'])) {
for($i=0;$i<=count($_FILES['wp_custom_attachment']['name']);$i++){

$_FILES['wp_custom_attachment']['name'][ $i ];
  if ( '' != $_FILES['wp_custom_attachment']['name'][ $i ] ) {

  $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'][ $i ], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name'][ $i ]));

if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
}
$images[] = $upload['url'];
  }




}

if(count($images)==0){
$images =$_POST['save_images'];
}else{
$images = base64_encode(json_encode($images));
}

   add_post_meta($post_id, 'wp_custom_attachment', $images);
    update_post_meta($post_id, 'wp_custom_attachment', $images); 

}

}

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');

Tuesday 5 April 2016

Add Gallery as custom field in wordpress

Hello,

If you have gallery as custom field then see below example.
i have here application post type. i am implement galley save in this post. Please Check Below Code.

Add Gallery as custom field in wordpress 

This Is Your functions.php code

<?php
function plu_admin_enqueue() { 
   // if(!($condition_to_check_your_page))// adjust this if-condition according to your theme/plugin
     //  return;
    wp_enqueue_script('plupload-all');

    wp_register_script('myplupload',  get_stylesheet_directory_uri() .'/js/myplupload.js', array('jquery'));

    wp_enqueue_script('myplupload');

    wp_register_style('myplupload', get_stylesheet_directory_uri() .'/css/myplupload.css');
    wp_enqueue_style('myplupload');
}
add_action( 'admin_enqueue_scripts', 'plu_admin_enqueue' ); 


function plupload_admin_head() { 
// place js config array for plupload
    $plupload_init = array(
        'runtimes' => 'html5,silverlight,flash,html4',
        'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
        'container' => 'plupload-upload-ui', // will be adjusted per uploader
        'drop_element' => 'drag-drop-area', // will be adjusted per uploader
        'file_data_name' => 'async-upload', // will be adjusted per uploader
        'multiple_queues' => true,
        'max_file_size' => wp_max_upload_size() . 'b',
        'url' => admin_url('admin-ajax.php'),
        'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
        'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
        'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')),
        'multipart' => true,
        'urlstream_upload' => true,
        'multi_selection' => false, // will be added per uploader
         // additional post data to send to our ajax hook
        'multipart_params' => array(
            '_ajax_nonce' => "", // will be added per uploader
            'action' => 'plupload_action', // the ajax action name
            'imgid' => 0 // will be added per uploader
        )
    );
?>
<script type="text/javascript"> 
    var base_plupload_config=<?php echo json_encode($plupload_init); ?>;
</script> 
<?php 
}
add_action("admin_head", "plupload_admin_head");

function g_plupload_action() {

    // check ajax noonce
    $imgid = $_POST["imgid"];
    check_ajax_referer($imgid . 'pluploadan');

    // handle file upload
    $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action'));

    // send the uploaded file url in response
    echo $status['url'];
    exit;
}
add_action('wp_ajax_plupload_action', "g_plupload_action"); 


add_action('add_meta_boxes', 'add_upload_file_metaboxes');

function add_upload_file_metaboxes() {
    add_meta_box('swp_file_upload', 'File Upload', 'swp_file_upload', 'appilcations', 'normal', 'default');
}

function swp_file_upload() {
global $post;
 //$svalue =get_post_meta( get_the_ID(), 'img1', true );

 echo '<input type="hidden" name="podcastmeta_noncename" id="podcastmeta_noncename" value="'.
    wp_create_nonce(plugin_basename(__FILE__)).
    '" />';
    // Noncename needed to verify where the data originated
   
$id = "img1"; // this will be the name of form field. Image url(s) will be submitted in $_POST using this key. So if $id == “img1” then $_POST[“img1”] will have all the image urls

$svalue = ""; // this will be initial value of the above form field. Image urls.

$multiple = true; // allow multiple files upload

$width = null; // If you want to automatically resize all uploaded images then provide width here (in pixels)

$height = null; // If you want to automatically resize all uploaded images then provide height here (in pixels)
?>

<label>Upload Images</label> 
<input type="hidden" name="<?php echo $id; ?>" id="<?php echo $id; ?>" value="<?php echo get_post_meta( get_the_ID(), 'img1', true ); ?>" /> 
<div class="plupload-upload-uic hide-if-no-js <?php if ($multiple): ?>plupload-upload-uic-multiple<?php endif; ?>" id="<?php echo $id; ?>plupload-upload-ui"> 
    <input id="<?php echo $id; ?>plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" />
    <span class="ajaxnonceplu" id="ajaxnonceplu<?php echo wp_create_nonce($id . 'pluploadan'); ?>"></span>
    <?php if ($width && $height): ?>
            <span class="plupload-resize"></span><span class="plupload-width" id="plupload-width<?php echo $width; ?>"></span>
            <span class="plupload-height" id="plupload-height<?php echo $height; ?>"></span>
    <?php endif; ?>
    <div class="filelist"></div>
</div> 
<div class="plupload-thumbs <?php if ($multiple): ?>plupload-thumbs-multiple<?php endif; ?>" id="<?php echo $id; ?>plupload-thumbs"> 
</div> 
<div class="clear"></div>


<?php
//echo $svalue =get_post_meta( get_the_ID(), 'img1', true );
 }

function save_podcasts_meta($post_id, $post) {
    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if (!wp_verify_nonce($_POST['podcastmeta_noncename'], plugin_basename(__FILE__))) {
        return $post -> ID;
    }
    // Is the user allowed to edit the post?
    if (!current_user_can('edit_post', $post -> ID))
        return $post -> ID;
    // We need to find and save the data
    // We'll put it into an array to make it easier to loop though.
    $podcasts_meta['img1'] = $_POST['img1'];
    // Add values of $podcasts_meta as custom fields

    foreach($podcasts_meta as $key => $value) {
        if ($post -> post_type == 'revision') return;
         $value = implode(',', (array) $value);
 
        if (get_post_meta($post -> ID, $key, FALSE)) { // If the custom field already has a value it will update
            update_post_meta($post -> ID, $key, $value);
        } else { // If the custom field doesn't have a value it will add
            add_post_meta($post -> ID, $key, $value);
        }
        if (!$value) delete_post_meta($post -> ID, $key); // Delete if blank value
    }
}
add_action('save_post', 'save_podcasts_meta', 1, 2); // sav

added myplupload.js and myplupload.css in your theme folder.

myplupload.js code

    jQuery.fn.exists = function() { 
        return jQuery(this).length > 0;
    }
    jQuery(document).ready(function($) {
    
        if ($(".plupload-upload-uic").exists()) {
            var pconfig = false;
            $(".plupload-upload-uic").each(function() {
                var $this = $(this);
                var id1 = $this.attr("id");
                var imgId = id1.replace("plupload-upload-ui", "");
    
                plu_show_thumbs(imgId);
    
                pconfig = JSON.parse(JSON.stringify(base_plupload_config));
    
                pconfig["browse_button"] = imgId + pconfig["browse_button"];
                pconfig["container"] = imgId + pconfig["container"];
                pconfig["drop_element"] = imgId + pconfig["drop_element"];
                pconfig["file_data_name"] = imgId + pconfig["file_data_name"];
                pconfig["multipart_params"]["imgid"] = imgId;
                pconfig["multipart_params"]["_ajax_nonce"] = $this.find(".ajaxnonceplu").attr("id").replace("ajaxnonceplu", "");
    
                if ($this.hasClass("plupload-upload-uic-multiple")) {
                    pconfig["multi_selection"] = true;
                }
    
                if ($this.find(".plupload-resize").exists()) {
                    var w = parseInt($this.find(".plupload-width").attr("id").replace("plupload-width", ""));
                    var h = parseInt($this.find(".plupload-height").attr("id").replace("plupload-height", ""));
                    pconfig["resize"] = {
                        width: w,
                        height: h,
                        quality: 90
                    };
                }
    
                var uploader = new plupload.Uploader(pconfig);
    
                uploader.bind('Init', function(up) {
    
                });
    
                uploader.init();
    
                // a file was added in the queue
                uploader.bind('FilesAdded', function(up, files) {
                    $.each(files, function(i, file) {
                        $this.find('.filelist').append('
' +
    
                        file.name + '
(' + plupload.formatSize(0) + '/' + plupload.formatSize(file.size) + ') ' + '
');
                    });
    
                    up.refresh();
                    up.start();
                });
    
                uploader.bind('UploadProgress', function(up, file) {
    
                    $('#' + file.id + " .fileprogress").width(file.percent + "%");
                    $('#' + file.id + " span").html(plupload.formatSize(parseInt(file.size * file.percent / 100)));
                });
    
                // a file was uploaded
                uploader.bind('FileUploaded', function(up, file, response) {
    
    
                    $('#' + file.id).fadeOut();
                    response = response["response"]
                    // add url to the hidden field
                    if ($this.hasClass("plupload-upload-uic-multiple")) {
                        // multiple
                        var v1 = $.trim($("#" + imgId).val());
                        if (v1) {
                            v1 = v1 + "," + response;
                        } else {
                            v1 = response;
                        }
                        $("#" + imgId).val(v1);
                    } else {
                        // single
                        $("#" + imgId).val(response + "");
                    }
                    // show thumbs
                    plu_show_thumbs(imgId);
                });
            });
        }
    });
    
    function plu_show_thumbs(imgId) { 
        var $ = jQuery;
        var thumbsC = $("#" + imgId + "plupload-thumbs");
        thumbsC.html("");
        // get urls
        var imagesS = $("#" + imgId).val();
        var images = imagesS.split(",");
        for (var i = 0; i < images.length; i++) {
            if (images[i]) {
                var thumb = $('
');
                thumbsC.append(thumb);
                thumb.find("a").click(function() {
                    var ki = $(this).attr("id").replace("thumbremovelink" + imgId, "");
                    ki = parseInt(ki);
                    var kimages = [];
                    imagesS = $("#" + imgId).val();
                    images = imagesS.split(",");
                    for (var j = 0; j < images.length; j++) {
                        if (j != ki) {
                            kimages[kimages.length] = images[j];
                        }
                    }
                    $("#" + imgId).val(kimages.join());
                    plu_show_thumbs(imgId);
                    return false;
                });
            }
        }
        if (images.length > 1) {
            thumbsC.sortable({
                update: function(event, ui) {
                    var kimages = [];
                    thumbsC.find("img").each(function() {
                        kimages[kimages.length] = $(this).attr("src");
                        $("#" + imgId).val(kimages.join());
                        plu_show_thumbs(imgId);
                    });
                }
            });
            thumbsC.disableSelection();
        }
    }

here added myplupload.css
    .filelist {
        width: 60%;
    }
    .filelist .file {
        padding: 5px;
        background: #ececec;
        border: solid 1px #ccc;
        margin-bottom: 4px;
    }
    .filelist .fileprogress {
        width: 0%;
        background: #B7C53D;
        height: 5px;
    }
    .plupload-thumbs {
    
    }
    .plupload-thumbs .thumb {
        width: 50px;
        padding-right: 5px;
        float: left;
    }
    .plupload-thumbs .thumb img {
        width: 50px;
        height: 50px;
    }
    .ui-sortable  .thumb img {
        cursor: pointer;
    }


if you want download code please click here


Sunday 3 April 2016

How can I replace whitespace with underscores in php?

The \s character class will match whitespace characters. I've added the + quantifier to collapse multiple whitespace to one _. If you don't want that, remove the +

$picture =preg_replace('/\s+/', '_', uniqid()."_".$image_name);

Wednesday 30 March 2016

Custom Url ReWrite in Wordpress

here Example How To generate custom url rewrite in wordpress

Check it

function create_custom_rewrite_rules() {
global $wp_rewrite;

$rewrite_tag = '%patentID%';
$wp_rewrite->add_rewrite_tag( $rewrite_tag, '(.+?)', 'patentID=' );
$rewrite_keywords_structure = $wp_rewrite->root . "%pagename%/$rewrite_tag/";
$new_rule = $wp_rewrite->generate_rewrite_rules( $rewrite_keywords_structure );

$wp_rewrite->rules = $new_rule + $wp_rewrite->rules;

return $wp_rewrite->rules;
}

function add_custom_page_variables( $public_query_vars ) {
$public_query_vars[] = 'patentID';

return $public_query_vars;

}

function flush_rewrite_rules132() {

global $wp_rewrite;

$wp_rewrite->flush_rules();

}

add_action( 'init', 'flush_rewrite_rules132' );
add_action( 'generate_rewrite_rules', 'create_custom_rewrite_rules' );
add_filter( 'query_vars', 'add_custom_page_variables' );


You can get this using

$patentID = get_query_var('patentID');  in you template

Tuesday 22 March 2016

added custom loder in ajax request in wordpress

added custom loder in ajax request in wordpress

function ajaxindicatorstart(text)
{
if(jQuery('body').find('#resultLoading').attr('id') != 'resultLoading'){
jQuery('body').append('<div id="resultLoading" style="display:none"><div><img src="<?php echo wp_get_attachment_url( 391 ); ?>"><div>'+text+'</div></div><div class="bg"></div></div>');
}

jQuery('#resultLoading').css({
'width':'100%',
'height':'100%',
'position':'fixed',
'z-index':'10000000',
'top':'0',
'left':'0',
'right':'0',
'bottom':'0',
'margin':'auto'
});

jQuery('#resultLoading .bg').css({
'background':'#000000',
'opacity':'0.7',
'width':'100%',
'height':'100%',
'position':'absolute',
'top':'0'
});

jQuery('#resultLoading>div:first').css({
'width': '250px',
'height':'75px',
'text-align': 'center',
'position': 'fixed',
'top':'0',
'left':'0',
'right':'0',
'bottom':'0',
'margin':'auto',
'font-size':'16px',
'z-index':'10',
'color':'#ffffff'

});

    jQuery('#resultLoading .bg').height('100%');
        jQuery('#resultLoading').fadeIn(300);
    jQuery('body').css('cursor', 'wait');
}

function ajaxindicatorstop()
{
    jQuery('#resultLoading .bg').height('100%');
        jQuery('#resultLoading').fadeOut(300);
    jQuery('body').css('cursor', 'default');
}
jQuery(document).ajaxStart(function () {
   //show ajax indicator
ajaxindicatorstart('please wait..');
  }).ajaxStop(function () {
//hide ajax indicator
ajaxindicatorstop();
  });

Wednesday 16 March 2016

Insert custom post data with custom field using ajax in wordpress

Insert custom post data  with custom field using ajax in wordpress



<!-- This code in your custom template -->

<script>
 jQuery(document).ready(function() {
var form = jQuery( "#newCustomerForm" );


jQuery('.alu1').click(function(){

  var  checkForm = form.valid();
 
  if(checkForm != false){

var newCustomerForm = jQuery('#newCustomerForm').serializeArray();
jQuery.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: newCustomerForm,
success: function(data){

if(data == "success"){


}
jQuery("form").trigger("reset");
}


});
}
return false;
});
 });
</script>
<form name="test" id="newCustomerForm">
                              <div class="input-group">
                              <span class="input-group-addon"><i class="fa fa-user"></i></span>
                              <input  class="form-control" type="text" placeholder="Enter your name" name="alu_name" required="required" />
                             
                              </div>
                              <div class="input-group">
                              <span class="input-group-addon"><i class="fa fa-envelope-o"></i></span>
                             
                                <input id="exampleInputEmail1" class="form-control" type="email" placeholder="Enter your Email" name="alu_email" required="required" />
                                </div>
                               
                                <div class="input-group">
                              <span class="input-group-addon"><i class="fa fa-mobile"></i></span>
                                <input  class="form-control" type="number" placeholder="Enter your Mobile no" name="alu_mobile" required="required" />
                                </div>
                               
                                <div class="input-group">
                              <span class="input-group-addon"><i class="fa fa-university"></i></span>
                                <input  class="form-control" type="text" placeholder="Enter your city name" name="alu_city" required="required" />
                                </div>
                               
                                <div class="input-group">
                              <span class="input-group-addon"><i class="fa fa-commenting"></i></span>
                                <textarea id="exampleTextarea" class="form-control" rows="3" name="alu_message" required="required"></textarea>
                                </div>
                                <button type="button" class="btn primary alu1">Submit</button>
                                 <input type="hidden" name="submitted" id="submitted" value="true" />
    <input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'form-nonce' );?>" />  
                            <input type="hidden" name="action" id="my_action" value="my_action" />                   
                                </form>
   
   
   
   
    <?php                           

/** In Your Function File **/
              function myFunction(){
   //do something
  
  
  
 
  

$alu_name=    sanitize_meta('name_alu_c1',$_POST['alu_name'],'user');
$alu_email=    sanitize_email($_POST['alu_email']);
$alu_mobile=    sanitize_meta('phone_alu_c1',$_POST['alu_mobile'],'user');
$alu_city=    sanitize_meta('city_alu_c1',$_POST['alu_city'],'user');
$alu_message=    sanitize_meta('message_alu_c1',$_POST['alu_message'],'user');

$my_cptpost_args = array(
          
            'post_title' => $alu_name,
            'post_status'   => 'publish',
            'post_type' => "alu_contact1",
);
$cpt_id = wp_insert_post($my_cptpost_args, $wp_error );
if($cpt_id){
add_post_meta($cpt_id, 'name_alu_c1', $alu_name, true);//here insert two custom field data.
add_post_meta($cpt_id, 'email_address_alu_c1', $alu_email, true);//here insert two custom field data.
add_post_meta($cpt_id, 'phone_alu_c1', $alu_mobile, true);//here insert two custom field data.
add_post_meta($cpt_id, 'city_alu_c1', $alu_city, true); //here insert two custom field data..
add_post_meta($cpt_id, 'message_alu_c1', $alu_message, true); //here insert two custom field data..

$test = wp_mail( $alu_email, "Contact Us", "Thank You For Contact us" );

echo "success";
}
       
       
   die();
}





add_action('wp_ajax_my_action', 'myFunction');           // for logged in user
add_action('wp_ajax_nopriv_my_action', 'myFunction');    // if user not logged in