Tuesday, December 27, 2022

wordpress crud with file upload ajax frontend

Hello

Today I saw you crud  ajax operation with file upload in front side of wordpress website. Create a plugin for it, make shortcode and use it in wordpress page/post. 

Make file structure like this.




FILE : ajax-front.php

<?php

/*

Plugin Name: AJAX FRONT CRUD with media upload

Plugin URI: #

Description: A simple plugin that allows you to perform Create (INSERT), Read (SELECT), Update, Delete, File upload operations with ajax in FRONT SIDE.

Version: 1.0.0

Author: Chirag

Author URI: #

License: GPL2

*/

defined( 'ABSPATH' ) || exit;


/**

 * DEFINE PATHS

 */

global $wpdb;

define( 'MY_FRONT_CRUDURL', plugin_dir_url( __FILE__ ) );

define( 'MY_FRONT_CRUDPATH', plugin_dir_path( __FILE__ ));


//load css and js

function frontend_cssjs() {

  wp_register_style( 'customcss', MY_FRONT_CRUDURL.'/css/style.css', false, '1.0.0' );

  wp_enqueue_style( 'customcss' );


  wp_register_style('prefix_bootstrapcss', 'https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css');

  wp_enqueue_style('prefix_bootstrapcss');

  wp_register_script('prefix_bootstrapjs', 'https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js');

  wp_enqueue_script('prefix_bootstrapjs');


  wp_enqueue_script( 'my_jquery', MY_FRONT_CRUDURL. 'js/jQuery.min.js' );

  wp_enqueue_script( 'myjs', MY_FRONT_CRUDURL. 'js/crud.js' );

  wp_localize_script( 'myjs', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));


// Enqueue WordPress media scripts

    //wp_enqueue_media();

    // Enqueue custom script that will interact with wp.media

    //wp_enqueue_script( 'myprefix_script', plugins_url( '/js/myscript.js' , __FILE__ ), array('jquery'), '0.1' );

}

add_action('wp_enqueue_scripts','frontend_cssjs');




function pwwp_enqueue_my_scripts() {

    // jQuery is stated as a dependancy of bootstrap-js - it will be loaded by WordPress before the BS scripts 

    wp_enqueue_script( 'bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap javascript goodness

}

add_action('wp_enqueue_scripts', 'pwwp_enqueue_my_scripts');


function pwwp_enqueue_my_styles() {

    wp_enqueue_style( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );


    // this will add the stylesheet from it's default theme location if your theme doesn't already

    //wp_enqueue_style( 'my-style', get_template_directory_uri() . '/style.css');

}

add_action('wp_enqueue_scripts', 'pwwp_enqueue_my_styles');





//activation hook

register_activation_hook( __FILE__, 'createfrontcrud');

function createfrontcrud() {

  global $wpdb;

  $charset_collate = $wpdb->get_charset_collate();

  $table_name = $wpdb->prefix . 'crudfront';

  $sql = "CREATE TABLE `$table_name` (

    `user_id` int(11) NOT NULL AUTO_INCREMENT,

    `name` varchar(220) DEFAULT NULL,

    `email` varchar(220) DEFAULT NULL,

    `filepath` varchar(256) DEFAULT NULL,

    PRIMARY KEY(user_id)

    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta($sql);

  }

}


require_once(MY_FRONT_CRUDPATH.'/ajax_action.php');



//[frontend_crud]

//add_shortcode('frontendcrudnew','front_crud_file');

function register_shortcodes(){

   add_shortcode('frontendcrudnew', 'front_crud_file');

}

add_action( 'init', 'register_shortcodes');


//display data

function front_crud_file(){ 

html_addbuton();

html_display_data();

edit_data();

}



function html_addbuton(){ ?>

<!-- Button trigger modal -->

<div class="">

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">

    Insert Data

  </button>

  <div id="msg"></div>

</div>

<!-- Modal -->

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

  <div class="modal-dialog" role="document">

    <div class="modal-content">

      <div class="modal-header">

        <h4 class="modal-title" id="myModalLabel">Add page for under construction</h4>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

      </div>

      <div class="modal-body">

          <div class="wqsubmit_message"></div>


          <form name="insertform" id="insertform" enctype="multipart/form-data">

            <table>

              <tbody>

                <tr>

                  <td><input type="text" value="AUTO_GENERATED" disabled></td>

                </tr>

                <tr>

                  <td><input type="text" id="newname" name="newname" placeholder="Name Here"></td>

                </tr>

                <tr>

                  <td><input type="text" id="newemail" name="newemail" placeholder="Email ID Here"></td>

                </tr>

                <tr>

<td>

<input type="file" name="file1" id="file1">

</td>

                </tr>

              </tbody>

            </table>

          

        </form>


      </div>

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary" id="savedata" name="savedata" >Insert Data</button>

        <!-- <div><input type="submit" class="btn btn-primary wqsubmit_button" id="wqadd" value="Add" /></div> -->

        

        <!-- <input type="submit" id="savedata" name="savedata" class="button button-primary" value="Save Data"> -->

      </div>

    </div>

  </div>

</div>

<!-- END Modal -->

<?php

}


function html_display_data(){

?>

<div class="wrap">

    <h2>DATA FRONTEND ALL</h2>

    <table class="wp-list-table widefat striped">

      <thead>

        <tr>

          <th width="5%">User ID</th>

          <th width="20%">Name</th>

          <th width="20%">Email Address</th>

          <th width="45%">Image</th>

          <th width="10%">Actions</th>

        </tr>

      </thead>

      <tbody>

        

        <?php

        global $wpdb;

        $table_name = $wpdb->prefix . 'crudfront';

          $result = $wpdb->get_results("SELECT * FROM $table_name");

          //print_r($result);

          $rowcount = count((array)$result);

          //echo "c:".$rowcount;

          //echo $last_query = $wpdb->last_query;

          if ($rowcount == 0) {

            echo "<tr> <td colspan='5'>No data found! </td></tr>";

          } else { 

            foreach ($result as $print) {

              ?>

                <tr id="user_<?php echo $print->user_id; ?>">

                  <td width='5%' id=""><?php echo $print->user_id; ?></td>

                  <td width='20%' id="inputUsername_<?php echo $print->user_id; ?>"><?php echo $print->name; ?></td>

                  <td width='20%' id="inputUserEmail_<?php echo $print->user_id; ?>"><?php echo $print->email; ?></td>

                  <td width='45%'> <img id="inputUserFile_<?php echo $print->user_id; ?>" height="250px" width="250px" src="<?php echo $print->filepath; ?>" alt=""> </td>

                  <td width='10%'>

                    <form name="formaction_<?php echo $print->user_id; ?>" id="formaction_<?php echo $print->user_id; ?>">

                      <input type="hidden" name="userid_delete" id="userid_delete" value="<?php echo $print->user_id; ?>">

                    <!-- <a href='admin.php?page=crud%2Fcrud.php&upt=$print->user_id'>

                      <button type='button'>UPDATE</button>

                    </a>  -->

                    <a href="#edit_user" class="open-edit_user" data-toggle="modal" data-user_id="<?php echo $print->user_id; ?>" onclick="goDoSomething(this);"> 

                      <span class="glyphicon glyphicon-edit">EDIT</span> 

                    </a>

                    <!-- <a href='admin.php?page=crud%2Fcrud.php&del=$print->user_id'> -->

                      <button type='button' data-user_id="<?php echo $print->user_id; ?>" onclick="DeleteData(this);">DELETE</button>

                    <!-- </a> -->

                  </form>

                  </td>

                </tr>

              

           <?php }

          }

        ?>

      </tbody>  

    </table>

    <br>

    <br>

    

  </div>

<?php

}


function edit_data(){

?>

<div class="modal fade" id="edit_user" role="dialog"> 

  <div class="modal-dialog">   

    <div class="modal-content"> 

      <div class="modal-header">   

        <h4 class="modal-title">

          <b>User Registration EDIT Form</b>

          <span id="uid"> </span>

        </h4> 

        <button type="button" class="close" data-dismiss="modal">&times;</button>   

      </div> 

      <div class="modal-body">   

        <div class="fetched_user"></div> 

        <div class="wqsubmit_message1"></div>


          <form name="editform" id="editform">

            <table>

              <tbody>

                <tr>

                  <td><input id="userid_input" type="text" value="" disabled>

                      <input type="hidden" name="userid" id="userid" value="">

                  </td>

                </tr>

                <tr>

                  <td><input type="text" id="editnewname" name="editnewname" placeholder="Name Here"></td>

                </tr>

                <tr>

                  <td><input type="text" id="editnewemail" name="editnewemail" placeholder="Email ID Here"></td>

                </tr>

                <tr>

<td>

<img src="" id="editfile" name="editfile" width="250px" height="250px">

<input type="hidden" id="editfile_hidden" name="editfile_hidden" value="">

<input type="file" name="fileedit" id="fileedit" value="">

</td>

                </tr>

              </tbody>

            </table>

          

          </form>

      </div> 

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary" id="updatedata" name="updatedata" >Update Data</button>

      </div> 

    </div>

  </div>

</div> <!--Edit Modal close-->

<?php

}


//deactive plugin

register_deactivation_hook( __FILE__, 'deactivate_crudfunction' );

function deactivate_crudfunction(){

global $wpdb;

  $table_name = $wpdb->prefix . 'crudfront';

  $sql = "DROP TABLE IF EXISTS $table_name";

  $wpdb->query($sql);

}


FILE : ajax_action.php

<?php
add_action('wp_ajax_ajaxfrontend','ajax_front_insert');
add_action('wp_ajax_nopriv_ajaxfrontend','ajax_front_insert');

function ajax_front_insert() {
  global $wpdb;
  //print_r($_POST); print_r($_FILES['file']); exit;
  $table_name = $wpdb->prefix . 'crudfront';
  //echo $filename=$_FILES['file1']['name']; exit();

  //file upload

  if (isset($_FILES['file1'] ) && !empty($_FILES['file1']['name']) ){
    $allowedExts = array("jpeg", "jpg", "png", "bmp", "gif");
    $temp = explode(".", $_FILES["file1"]["name"]);
    $extension = end($temp);
    if ( in_array($extension, $allowedExts)){
       if ( ($_FILES["file1"]["error"] > 0) && ($_FILES['file1']['size'] <= 3145728 ))
        {
            $response = array(
                "status" => 'error',
                "message" => 'ERROR Return Code: '. $_FILES["file1"]["error"],
                );
        }
        else{
          $uploadedfile = $_FILES['file1'];
          $upload_name = $_FILES['file1']['name'];
          $tempname = $_FILES["file1"]["tmp_name"];
          //$uploads = wp_upload_dir();
          //$filepath = $uploads['path']."/$upload_name";
          $filepath = MY_FRONT_CRUDPATH."imgs/$upload_name";
          if ( ! function_exists( 'wp_handle_upload' ) )
          {
              require_once( ABSPATH . 'wp-admin/includes/file.php' );
          }
          require_once( ABSPATH . 'wp-admin/includes/image.php' );
          $upload_overrides = array( 'test_form' => false );
          $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); // default wordpress file upload
          //$movefile = wp_upload_bits($uploadedfile, null, file_get_contents($_FILES["file1"]["tmp_name"]));
          //$movefile = move_uploaded_file($tempname,$filepath);
          if ( $movefile && !isset( $movefile['error'] )  ) {
              $file = $movefile['file'];
              $url = $movefile['url'];
              $type = $movefile['type'];

              $attachment = array(
                  'post_mime_type' => $type ,
                  'post_title' => $upload_name,
                  'post_content' => 'File '.$upload_name,
                  'post_status' => 'inherit'
                  );

              $attach_id=wp_insert_attachment( $attachment, $file, 0);
              $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
              wp_update_attachment_metadata( $attach_id, $attach_data );
          }
          $response = array(
            "status" => 'success',
            "url" => $url
          );


        }

    }
    else
    {
        $response = array(
            "status" => 'error',
            "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
            );
    }
  } else {
    // no file uploaded {"status":"success","url":"http:\/\/localhost\/wordpress63\/wp-content\/uploads\/2022\/12\/blue-smart-watch-1.jpg"} Data Has Inserted Successfully

    $upload_name = '';
    
  }
  //print json_encode($response);
  //exit;
  //end file upload
  $sql = "SELECT * FROM `$table_name` WHERE `name` = '".$_POST['newname']."' AND `email` = '".$_POST['newemail']."' ORDER BY `user_id` DESC" ;
  //echo $sql;
  $wpdb->get_row($sql);
  if($wpdb->num_rows < 1) {
    $query = $wpdb->insert($table_name , array(
      "name" => $_POST['newname'],
      "email" => $_POST['newemail'],
      "filepath" => $url
    ));

    $last_query = $wpdb->last_query;
    if ($query == true) {
      //$response = array('message'=>'Data Has Inserted Successfully', 'rescode'=>200);
      $response = '<span class="alert alert-success"> Data Has Inserted Successfully </span>';
    } else {
       $response = '<span class="alert alert-danger"> Data Not Saved </span>';
    }
    
  } else {
    $response = '<span class="alert alert-info"> Data Has Already Exist </span>';
  }
  echo $response;
  exit();
  wp_die();
}



add_action('wp_ajax_edituserdata','ajaxEditData');
add_action('wp_ajax_nopriv_edituserdata','ajaxEditData');

function ajaxEditData() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'crudfront';
  $wpdb->get_row( "SELECT * FROM `$table_name` WHERE `name` = '".$_POST['editnewname']."' AND `email` = '".$_POST['editnewemail']."' AND `user_id`!='".$_POST['userid']."' " );
  if($wpdb->num_rows < 1) {

    //file upload
    if (isset($_FILES['fileedit'] ) && !empty($_FILES['fileedit']['name']) ){
      $allowedExts = array("jpeg", "jpg", "png", "bmp", "gif");
      $temp = explode(".", $_FILES["fileedit"]["name"]);
      $extension = end($temp);
      if ( in_array($extension, $allowedExts)){
         if ( ($_FILES["fileedit"]["error"] > 0) && ($_FILES['fileedit']['size'] <= 3145728 ))
          {
              $response = array(
                  "status" => 'error',
                  "message" => 'ERROR Return Code: '. $_FILES["fileedit"]["error"],
                  );
          }
          else{
            $uploadedfile = $_FILES['fileedit'];
            $upload_name = $_FILES['fileedit']['name'];
            $tempname = $_FILES["fileedit"]["tmp_name"];
            //$uploads = wp_upload_dir();
            //$filepath = $uploads['path']."/$upload_name";
            $filepath = MY_FRONT_CRUDPATH."imgs/$upload_name";
            if ( ! function_exists( 'wp_handle_upload' ) )
            {
                require_once( ABSPATH . 'wp-admin/includes/file.php' );
            }
            require_once( ABSPATH . 'wp-admin/includes/image.php' );
            $upload_overrides = array( 'test_form' => false );
            $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); // default wordpress file upload
            //$movefile = wp_upload_bits($uploadedfile, null, file_get_contents($_FILES["file1"]["tmp_name"]));
            //$movefile = move_uploaded_file($tempname,$filepath);
            if ( $movefile && !isset( $movefile['error'] )  ) {
                $file = $movefile['file'];
                $url = $movefile['url'];
                $type = $movefile['type'];

                $attachment = array(
                    'post_mime_type' => $type ,
                    'post_title' => $upload_name,
                    'post_content' => 'File '.$upload_name,
                    'post_status' => 'inherit'
                    );

                $attach_id=wp_insert_attachment( $attachment, $file, 0);
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                wp_update_attachment_metadata( $attach_id, $attach_data );
            }
            $response = array(
              "status" => 'success',
              "url" => $url
            );


          }

      }
      else
      {
          $response = array(
              "status" => 'error',
              "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
              );
      }
    } else {
      // no file uploaded {"status":"success","url":"http:\/\/localhost\/wordpress63\/wp-content\/uploads\/2022\/12\/blue-smart-watch-1.jpg"} Data Has Inserted Successfully
      //$upload_name = $_POST['editfile_hidden'];
      $url = $_POST['editfile_hidden'];
    }

    $updatedata = $wpdb->update( $table_name, array(
      "name" => $_POST['editnewname'],
      "email" => $_POST['editnewemail'],
      "filepath" => $url
      //"updated_at" => time()
    ), array('user_id' => $_POST['userid']) );

    //echo $last_query = $wpdb->last_query;

    if ($updatedata == true) {
      //$response = array('message'=>'Data Has Updated Successfully', 'rescode'=>200);
      $response = '<span class="alert alert-success"> Data Has Updated Successfully </span>';
    } else {
      $response = '<span class="alert alert-danger"> Data Not Saved </span>';
    }


    
  } else {
    //$response = array('message'=>'Data Has Already Exist', 'rescode'=>404);
    $response = '<span class="alert alert-warning"> Data Has Already Same! </span>';
  }
  //echo json_encode($response);
  echo $response;
  exit();
  wp_die();
}


add_action('wp_ajax_delete_data','wqedit_entry_delete_data');
add_action('wp_ajax_nopriv_delete_data','wqedit_entry_delete_data');
function wqedit_entry_delete_data() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'crudfront'; 
  //$_POST['editnewname'];
  //print_r($_POST); exit(); 
  $userid_delete = $_POST['userid_delete'];
  $query = $wpdb->delete( $table_name, array( 'user_id' => $userid_delete ) );
  //echo $last_query = $wpdb->last_query;
  if ($query == true) {
    $response = "1";
  } else {
    $response = "2";
  }
  echo $response;
  exit();
  wp_die();
}

FILE : css/style.css


.wqmessage {
  color: red;
  font-size: 16px;
}
.wqsubmit_message {
  font-size: 16px;
}
.wqtextfield {
  width: 100%;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 8px;
}
.wqsubmit_button {
  background-color: lightseagreen;
  border: none;
  color: white;
  padding: 10px;
  cursor: pointer;
  border-radius: 8px;
  width: 100%;
}
.wqlabel {
  font-size: 20px;
  margin-bottom: 10px;
}
.wqpage_heading {
  font-size: 25px;
  text-align: center;
}

#insertform {
    float: left;
    padding-top: 20px;
}
.wqsubmit_message{padding: 10px;}


FILE: js/crud.js

jQuery(document).ready(function(){
   //$(document).on('submit','#insertform', function(e) {
   jQuery("#savedata").click( function(e) {
    e.preventDefault();
    //alert('aaya');
    $('.wqmessage').html('');
    $('.wqsubmit_message').html('');

      var newname = $('#newname').val();
      var newemail = $('#newemail').val();

      var regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      if(regex.test(newemail)){
       var emailcheck = true;
      }
      else{
       var emailcheck = false;
      }


    if(newname != '' && emailcheck == true) {
      var fd = new FormData(document.getElementById("insertform"));
      //var fd = new FormData(this);
      var action = 'ajaxfrontend';
      fd.append("action", action);

      //var form_data =jQuery('#insertform').serializeArray();
      //console.log(form_data);


      $.ajax({
        data: fd,
        //data: {action: "wqnew_entry", newname : newname, newemail: newemail},
        type: 'POST',
        url: ajax_var.ajaxurl,
        contentType: false,
           cache: false,
           processData:false,
        success: function(response) {
         //var res = JSON.stringify(response);
          //var res = JSON.parse(res);
          $('.wqsubmit_message').html(response);
          // if(res.rescode!='404') {
          //   $('#insertform')[0].reset();
          //   $('.wqsubmit_message').css('color','green');
          // } else {
          //   $('.wqsubmit_message').css('color','red');
          // }
          setTimeout(function() { location.reload(); }, 3500);
          //$(".entry-content").load("../showdata.php");
        }
      });
    } else {
      return false;
    }
  });



   //update data
   jQuery("#updatedata").click( function(e) {
      e.preventDefault();
      $('.wqmessage').html('');
      $('.wqsubmit_message1').html('');
      var userid = $('#userid').val();
      var editnewname = $('#editnewname').val();
      var editnewemail = $('#editnewemail').val();

      var regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      if(regex.test(editnewemail)){
       var emailcheck = true;
      }
      else{
       var emailcheck = false;
      }

      if(newname != '' && emailcheck == true) { 
        var fd = new FormData(document.getElementById("editform"));
        var action = 'edituserdata';
        fd.append("action", action);
//debugger;
        $.ajax({
          data: fd,
          type: 'POST',
          url: ajax_var.ajaxurl,
          contentType: false,
             cache: false,
             processData:false,
          success: function(response) {
            $('.wqsubmit_message1').html(response);
            setTimeout(function() { location.reload(); }, 3500);
          }
        });        
      }
      else {
        return false;
      }
   });

  });

function goDoSomething(d){     
    var uid = d.getAttribute("data-user_id");
    var username = $("#inputUsername_"+uid).text();
    var emailid = $("#inputUserEmail_"+uid).text();
    var filesrc = $("#inputUserFile_"+uid).attr('src');
    $("#userid_input").val(uid); 
    $("#userid").val(uid); 
    $("#editnewname").val(username);
    $("#editnewemail").val(emailid);
    //$('#editfile').attr('src','');
    $('#editfile').attr('src',filesrc);
    $('#editfile_hidden').val(filesrc);
}

//delete data
function DeleteData(d){ 
  var uid = d.getAttribute("data-user_id");
  //alert(uid);
  if (confirm('Are you sure ?')) {
        //$(this).prev('span.text').remove();
      //alert(uid);
    $('#msg').html('');
    var fd = new FormData(document.getElementById("formaction_"+uid));
    var action = 'delete_data';
    fd.append("action", action);
    $.ajax({
          data: fd,
          type: 'POST',
          url: ajax_var.ajaxurl,
          contentType: false,
             cache: false,
             processData:false,
          success: function(res) {
            $('#msg').html('<span class="alert alert-success"> Data Has DELETED Successfully </span>');
            $('#user_'+uid).remove();
            //setTimeout(function() { location.reload(); }, 4000);
          }
    });
  }
}

Now go to wp-admin area. open any page/post. Paste this shortcode to this : 
[frontendcrudnew]


These are some screenshots.





Monday, December 19, 2022

Wordpress ajax call on checkbox

Hello. Now I am explained how to make ajax call on checkbox checked in unchecked.

mainfile.php

<?php

/*

Plugin Name: Product Options With Conditions

Plugin URI: #

Description: You can set extra price for extra condition

Version: 1.0

Author: Chirag

Author URI: #

License: GPL2

*/


/**

 * DEFINE PATHS

 */

define( 'UC_PATH', plugin_dir_path( __FILE__ ) );

define( 'UC_FUNCTIONS_PATH', UC_PATH . 'includes/functions.php' );

define('CRUD_PLUGIN_PATH1', plugin_dir_path( __FILE__ ));

define( 'WP_PLUGIN_URL1', plugin_dir_url( __FILE__ ) );


if(!defined('ABSPATH')){ exit; }


add_action('admin_menu','addMenu');


function addMenu() {

  add_menu_page('Product Options1', 'Product Options2', 'manage_options' ,__FILE__, 'displaySetting', 'dashicons-wordpress');

}


//activate plugin and create table

register_activation_hook( __FILE__, 'unserConstructiontablecreate');

function unserConstructiontablecreate() {

  global $wpdb;

  global $table_name;

  $charset_collate = $wpdb->get_charset_collate();

  $table_name = $wpdb->prefix . 'custom_product_test';

  $sql = "CREATE TABLE IF NOT EXISTS `$table_name` (

  `cid` int(11) NOT NULL AUTO_INCREMENT,

  `productid` int(11) DEFAULT NULL,

  `labelname` VARCHAR(256) DEFAULT NULL,

  `inputtype` VARCHAR(256) DEFAULT NULL,

  `inputvalue` VARCHAR(256) DEFAULT NULL,

  `price` VARCHAR(256) DEFAULT NULL,

  `datetime` DATETIME DEFAULT NULL,

  `status` int(1) DEFAULT 1,

  PRIMARY KEY(cid)

  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

  ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta($sql);

  }

}


//include function file

require_once(UC_PATH.'/ajax_setdata.php');



function displaySetting() {

echo "<h2>Set all options</h2>";

htmlDisplayFunction();

}

function display_all_product($pid=NULL){

/*$args = array(

        'post_type'      => 'product',

        'posts_per_page' => 10,

        'product_cat'    => 'hoodies'

    );

    $loop = new WP_Query( $args );*/


    $products = wc_get_products( array( 'status' => 'publish', 'limit' => -1 ) );



  $select = '';

  $select.='<select name="selectProductId" id="selectProductId">';

  $select.='<option disabled>Select Product</option>';


  /*$pages = get_pages(); 

  foreach ($pages as $page_data) {

      $title = $page_data->post_title; 

      $pageid = $page_data->ID; 

      if (!empty($pid)) {

        if ($pid == $pageid ) {

          $selected = 'selected';

        } else {

          $selected = '';

        }

      }

      //echo "<pre>"; print_r($page_data);

      $select.='<option value="'.$pageid.'" '.$selected.' >'.$title.'</option>';

  }*/

    foreach ( $products as $product ){ 

    $productName= $product->get_title();

    $productid = $product->get_id();

    $select.='<option value="'.$productid.'" >'.$productName.' ('.$productid.')</option>';

    }

  $select.='</select>';

  return $select;

}

function htmlDisplayFunction(){ ?>

<div class="htmlDisplayFunction">

<form  method="post" name="setproductoptiontable" id="setproductoptiontable" accept-charset="utf-8">

<label for="pagename">Select Product</label>

<?php echo display_all_product(); ?>


<label>Add Input</label>

<select name="selectInput" id="selectInput" >

<option value="">Select Input Type</option>

<option value="textbox">Textbox</option>

<option value="checkbox">Checkbox</option>

<option value="radio">Radio Button</option>

</select>

</form>

</div>

<?php }


//add js

/*add_action( 'wp_enqueue_scripts', 'admin_enqueue_scripts1' );

function admin_enqueue_scripts1(){

  // JavaScript

    wp_enqueue_script( 'script-js1', plugins_url( '/admin/adminjs.js', __FILE__ ),array('jquery'));

  // Pass ajax_url to script.js

    wp_localize_script( 'script-js1', 'plugin_ajax_object',

            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}*/


add_action('wp_enqueue_scripts','ava_test_init');

function ava_test_init() {

  wp_enqueue_style( 'custom_css', plugins_url('/css/custom.css', __FILE__ ) );

  //wp_enqueue_script( 'jquerymain', 'http://code.jquery.com/jquery-1.9.1.js');

  wp_enqueue_style( 'jquery-css', 'https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css');

  wp_enqueue_script( 'jquery-js', 'https://code.jquery.com/jquery-1.10.2.js');

  wp_enqueue_script( 'jqueyui-js', 'https://code.jquery.com/ui/1.10.4/jquery-ui.js');

  //wp_enqueue_script( 'my_custom_script3', plugins_url('/js/script.js',__FILE__)  );


  //wp_localize_script( 'frontscript', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));

  //wp_localize_script( 'my_custom_script3', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));

  //wp_enqueue_script( 'ava-test-js', plugins_url( '/admin/adminjs.js', __FILE__ ));


  wp_enqueue_script( 'my_custom_script3', WP_PLUGIN_URL1. 'js/script.js' );

  //wp_enqueue_script( 'my_custom_script4', WP_PLUGIN_URL1. 'js/jQuery.min.js' );

  wp_localize_script( 'my_custom_script3', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));

}

//end js


add_action('admin_footer','adminfooterjscode' ); // For back-end


function  adminfooterjscode()

{

  //echo "<script type=\"text/javascript\">alert('submit clicked');</script>";

  ?>

    <script type="text/javascript">

    /*jQuery(document).ready(function($){

$("#selectInput").change(function () {

        var inputvalue = this.value;

        if (inputvalue == 'textbox') {


        }

    });

});*/



    </script>

  <?php

}

?>


<?php

//display on single product page

add_action( 'woocommerce_before_add_to_cart_button', 'wpo_wcpdf_product_custom_field', 10, 3 );

function wpo_wcpdf_product_custom_field () {

  global $wpdb;

  global $product;

  $html_extra=$html_inputtype='';

  $pid = $product->get_id();

  $table_name = $wpdb->prefix . 'custom_product_test';

  $results = $wpdb->get_results("SELECT * FROM $table_name WHERE `productid` = $pid");

  $rowcount = count((array)$results);

  if ($rowcount > 0) {

    //changePrice($pid);

    $html_extra.= "<div class='newoptiondata' id='newoptiondata'>";

    $html_extra.="<table>";

    foreach ($results as $print) {

      $fee = $print->price;

      $html_extra.="<tr>";

      $html_extra.= "<td>".$print->labelname."(".$fee.")"."</td>";


      if ($print->inputtype == 'textbox') {

        $html_inputtype.="<input type='text' name='textbox' value='".$print->inputvalue."'>";

      }

      $html_extra.= "<td>".$html_inputtype."</td>";

      $html_extra.= "</tr>";

    }

    $html_extra.="</table>";

    $html_extra.=display_html_new($pid);

    $html_extra.="</div>";

  }

   //echo $html_extra;

}

//end

?>

<?php

/*

<!-- <div class="textboxdiv">

<label>Enter Lable for input text</label>

<input type="text" value="" name="inputlabel" id="inputlabel">

<br>

<label>Enter input settings</label> <br>

</div> -->

*/

?>

<?php

function changePrice($pid){

  // add_filter('woocommerce_get_price','change_price', 10, 2);

  // add_filter('woocommerce_get_regular_price','change_price', 10, 2);

  // add_filter('woocommerce_get_sale_price','change_price', 10, 2);

  

}

function change_price($price, $product){ 

       if($product->id == '60'){ 

          //$price = "150"; 

       } 

       update_post_meta($product->id, '_regular_price', (float)$price);

    update_post_meta($product->id, '_price', (float)$price);

      return $price; 

}

function display_html_new($pid){ 

  //$pid = $product->get_id();

  

  echo '<div class="newclass1" id="newclass1">

    <table>

      <tbody>

        <tr>

          <td colspan="2">

            <input type="hidden" name="productid" id="productid" value="'.$pid.'" >

            <input type="checkbox" name="checkbox_text" id="checkbox_text"> 

            <label for="checkbox_text">Click for add Print Text (<span class="woocommerce-Price-currencySymbol">₹</span>5)</label>

          </td>

        </tr>

        <tr id="autoUpdate" class="autoUpdate" style="display:none;">

          <td>Write text for print</td>

          <td><input type="text" name="printtext1" id="printtext1" placeholder="Write print text here"></td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="radio" name="radiobutton" id="radiobutton1"> 

            <label for="radiobutton1">Red (<span class="woocommerce-Price-currencySymbol">₹</span>2)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="radio" name="radiobutton" id="radiobutton2"> 

            <label for="radiobutton2">Green (<span class="woocommerce-Price-currencySymbol">₹</span>3)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="radio" name="radiobutton" id="radiobutton3"> 

            <label for="radiobutton3">Blue (<span class="woocommerce-Price-currencySymbol">₹</span>4)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="checkbox" name="checkbox_2" id="checkbox_2"> 

            <label for="checkbox_2">Check for test1 (<span class="woocommerce-Price-currencySymbol">₹</span>5)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="checkbox" name="checkbox_3" id="checkbox_3"> 

            <label for="checkbox_3">Check for test2 (<span class="woocommerce-Price-currencySymbol">₹</span>5)</label>

          </td>

        </tr>

      </tbody>

    </table>

  </div>';


}

?>


script.js

$(document).ready(function () {

$('#checkbox_text').change(function () {

if (this.checked){

$('#autoUpdate').fadeIn('fast');

var op = 'add';

}

else {

$('#autoUpdate').fadeOut('fast');

var op = 'sub';

}

change_price(op);

});

function change_price(op){

var productid = $('#productid').val();

var optionvalue = '5';

var data = new FormData();

data.append("productid", productid);

data.append("optionvalue", optionvalue);

data.append("op", op);

data.append("action", "my_action2");

jQuery.post({

url: ajax_var.ajaxurl,

data: data,

contentType: false,

cache: false,

processData: false,

success: function (response) {

//$('.wqsubmit_message').html(response);

//setTimeout(function() { location.reload(); }, 3500);

}

});

}

});


/ajax_setdata.php

<?php 

//echo "chhhh";

add_action( 'wp_ajax_my_action2', 'my_action2' );

add_action( 'wp_ajax_nopriv_my_action2', 'my_action2' );


function my_action2(){

//print_r($_POST);

$productid = $_POST['productid'];

$optionvalue = $_POST['optionvalue'];

$op = $_POST['op'];


// Get an instance of the WC_Product object

$product = wc_get_product( $productid );


if ($op == 'add') {

$product_price = $product->get_price() + $optionvalue;

}

else{

$product_price = $product->get_price() - $optionvalue;

}

echo $product_price;

//$product['new_price'] = $product->get_sale_price() + $optionvalue;

//echo $product['new_price'];

// Set product prices

//$product->set_sale_price( $sale_price );

//$product->set_price( $price );


// Save data and update caches

//$product->save();

}

?>