Upload Image in wordpress as attachment

First Of all we need a Form

  • Then We need a Jquery For Ajax Request

  • jQuery('body').on('change','#files',function(){
    jQuery(this).parents('form').submit();
    });


    jQuery("form#data").submit(function(event){
    event.preventDefault();
    var formData = new FormData(jQuery(this)[0]);

    jQuery.ajax({
    url: ajaxUrl+'?action=cvf_upload_files',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
    var obj = jQuery.parseJSON(returndata);
    UploadedImageContain = obj;
    var attachment = [];
    if(jQuery("#attachment").length>=1){
    var attachmentData = jQuery("#attachment").val();
    attachmentData = attachmentData.split(',');

    }
    if(jQuery("ul#imagesContainerGallery").length>=1){
    jQuery("#imagesContainerGallery").remove();
    }

    jQuery("

      ").insertAfter(jQuery("#files").parent('form'));
      var cList = jQuery('ul#imagesContainerGallery');

      jQuery('.ImageSection').find('option').remove();

      jQuery('.ImageSection').append(jQuery('', {
      value: '',
      text :'Select'
      }));
      jQuery('.ImageSection').append(jQuery('', {
      value: 'media',
      text :'Media Library'
      }));

      var index = 1;
      jQuery.each(obj,function(k,v){
      attachment.push(k);
      var li =jQuery('

    • ')
      .addClass('ui-menu-item')
      .attr('role', 'menuitem')
      .appendTo(cList);
      var aaa =jQuery('')
      .attr('src', v)
      .appendTo(li);
      jQuery('.ImageSection').append(jQuery('', {
      value: k,
      text :'Photo'+index
      }));
      index++;
      });

      jQuery('.ImageSection').append(jQuery('', {
      value: 'NO',
      text :'No Photo'
      }));

      var attachment_new = jQuery('')
      .addClass('attachementCustom')
      .attr('value',attachment.toString())
      .attr('name','attachment')
      .attr('id',"attachment")
      .attr('type',"hidden")

      if(jQuery("#attachment").length>=1){
      jQuery("#attachment").remove();
      }
      jQuery(attachment_new).insertBefore("#files");

      }

      });

      return false;
      });

      Now next thing would be ajax function


      function cvf_upload_files_callback(){

      $parent_post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : 0;
      $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
      $max_file_size = 1024 * 500;
      $max_image_upload = 10;
      $wp_upload_dir = wp_upload_dir();
      $path = $wp_upload_dir['path'] . '/';
      $count = 0;
      $attach_id_array = array();
      $attachments = get_posts( array(
      'post_type' => 'attachment',
      'posts_per_page' => -1,
      'post_parent' => $parent_post_id,
      'exclude' => get_post_thumbnail_id()
      ) );
      if( $_SERVER['REQUEST_METHOD'] == "POST" ){
      foreach ( $_FILES['files']['name'] as $f => $name ) {
      $extension = pathinfo( $name, PATHINFO_EXTENSION );
      $new_filename = $this->cvf_td_generate_random_code( 20 ) . '.' . $extension;
      if ( $_FILES['files']['error'][$f] == 4 ) {
      continue;
      }

      if ( $_FILES['files']['error'][$f] == 0 ) {
      if ( $_FILES['files']['size'][$f] > $max_file_size ) {
      $upload_message[] = "$name is too large!.";
      continue;

      } elseif( ! in_array( strtolower( $extension ), $valid_formats ) ){
      $upload_message[] = "$name is not a valid format";
      continue;

      } else{
      if( move_uploaded_file( $_FILES["files"]["tmp_name"][$f], $path.$new_filename ) ) {

      $count++;

      $filename = $path.$new_filename;
      $filetype = wp_check_filetype( basename( $filename ), null );
      $wp_upload_dir = wp_upload_dir();
      $attachment = array(
      'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
      'post_mime_type' => $filetype['type'],
      'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
      'post_content' => '',
      'post_status' => 'inherit'
      );
      $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
      $attach_id_array[] = $attach_id;

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

      $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
      wp_update_attachment_metadata( $attach_id, $attach_data );

      }
      }
      }
      }

      }
      if ( isset( $upload_message ) ) :
      foreach ( $upload_message as $msg ){
      printf( __('

      %s

      ', 'wp-trade'), $msg );
      }
      endif;

      if( $count != 0 ){

      //printf( __('

      %d files added successfully!

      ', 'wp-trade'), $count );
      }

      $attachmentData = array();
      if(!empty($attach_id_array)):
      for($i=0;$i<count($attach_id_array);$i++){
      $attachmentData[$attach_id_array[$i]] = wp_get_attachment_url($attach_id_array[$i]);
      }
      endif;
      echo json_encode($attachmentData);
      exit();
      }

      function cvf_td_generate_random_code($length=10) {

      $string = '';
      $characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";

      for ($p = 0; $p < $length; $p++) {
      $string .= $characters[mt_rand(0, strlen($characters)-1)];
      }
      return $string;
      }

    • Email Template

      Here the example of email template wordpress function code
      $emailTempalte = 'assistant_mail.html';
      $template_name = get_bloginfo('template_url').'/custom/emailTemplate/'.$emailTempalte;
      $str = file_get_contents($template_name);
      $arrayContent= array('!!name!!'=>'Ritesh',
      '!!datetime!!' =>'27 aug 2016 Morning',
      '!!hospital!!' =>'QFG',
      '!!surgeon_name!!'=>'Joshi',
      '!!surgeon_address!!'=>'This is testing',
      '!!surgeon_number!!'=>'5452144122'
      );
      foreach($arrayContent as $key=>$vals){
      $str = str_replace( $key,$vals,$str);
      }
      wp_mail($to,$subject,$message,$headers);

      Here is the example of html file

      <p>Dear !!name!!,</p>
      <p>I would like to engage you for the following session </p>
      <p>!!datetime!!</p>
      <p>!!hospital!!</p>

      <p>Please confirmĀ  ASAP by return email, or phone as per the details below </p>
      <p><strong>Surgery name:</strong>!!surgery_name!!</p>
      <p><strong>Billing For Assistant:</strong>!!billing_for_assistants!!</p>

      <p>From</p>
      <p>!!surgeon_name!!</p>
      <p>!!surgeon_number!!</p>

       

      table listing display in admin

      if( ! class_exists( 'WP_List_Table' ) ) {
      require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
      }

      To create a table to your needs you have to derive a class from WP_List_Table:

      class My_List_Table extends WP_List_Table {
      }

      $myListTable = new My__List_Table();

      Usually this data would be read from the database:

      var $example_data = array(
      array('ID' => 1,'title' => 'Share point', 'author' => 'david'),
      array('ID' => 2, 'title' => 'Share point new','author' => 'smith'),
      array('ID' => 3, 'title' => 'Share point latest', 'author' => 'martin'),
      array('ID' => 4, 'title' => 'Share point wet', 'author' => 'johnson'),
      array('ID' => 5, 'title' => 'Share point usually', 'author' => 'Markque'),
      array('ID' => 6, 'title' => 'Share point test', 'author' => 'Seth Harwood')
      );

      we have to define some methods and variables:

      function get_columns(){
      $columns = array(
      'title' => 'Title',
      'author' => 'Author'
      );
      return $columns;
      }

      function prepare_items() {
      $columns = $this->get_columns();
      $hidden = array();
      $sortable = array();
      $this->_column_headers = array($columns, $hidden, $sortable);
      $this->items = $this->example_data;;
      }

      that will process any column for which no special method is defined:

      function column_default( $item, $column_name ) {
      switch( $column_name ) {
      case 'booktitle':
      case 'author':
      case 'isbn':
      return $item[ $column_name ];
      default:
      return print_r( $item, true ) ; //Show the whole array for troubleshooting purposes
      }
      }

      In our example the method will return the title for every column and if the column is not found it displays the content of the $item array for debugging purposes.

      These are the essential ingredients to define a custom list table class.

      function my_add_menu_items(){
      add_menu_page( 'My Plugin List Table', 'My List Table Example', 'activate_plugins', 'my_list_test', 'my_render_list_page' );
      }
      add_action( 'admin_menu', 'my_add_menu_items' );

      function my_render_list_page(){
      $myListTable = new My_Example_List_Table();
      echo '

      My List Table Test

      ';
      $myListTable->prepare_items();
      $myListTable->display();
      echo '

      ';
      }

      Change add to cart button text

      Change the add to cart text on single product pages

      WooCommerce <2.1


      add_filter( 'add_to_cart_text', 'woo_custom_cart_button_text' ); // < 2.1

      function woo_custom_cart_button_text() {

      return __( 'My Button Text', 'woocommerce' );

      }

      WooCommerce 2.1+

      add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' ); // 2.1 +

      function woo_custom_cart_button_text() {

      return __( 'My Button Text', 'woocommerce' );

      }

      Change the add to cart text on product archives

      WooCommerce <2.1

      add_filter( 'add_to_cart_text', 'woo_archive_custom_cart_button_text' ); // < 2.1

      function woo_archive_custom_cart_button_text() {

      return __( 'My Button Text', 'woocommerce' );

      }

      WooCommerce 2.1+

      add_filter( 'woocommerce_product_add_to_cart_text', 'woo_archive_custom_cart_button_text' ); // 2.1 +

      function woo_archive_custom_cart_button_text() {

      return __( 'My Button Text', 'woocommerce' );

      }

      Change the add to cart text on product archives by product types

      product_type;

      switch ( $product_type ) {
      case 'external':
      return __( 'Buy product', 'woocommerce' );
      break;
      case 'grouped':
      return __( 'View products', 'woocommerce' );
      break;
      case 'simple':
      return __( 'Add to cart', 'woocommerce' );
      break;
      case 'variable':
      return __( 'Select options', 'woocommerce' );
      break;
      default:
      return __( 'Read more', 'woocommerce' );
      }

      }

      Remove tab from woocommerce single product page

      vendor-tab
      For complete remove tab

       
      // Removes tabs from their original loaction
      remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );

      // Inserts tabs under the main right product content
      add_action( ‘woocommerce_single_product_summary’, ‘woocommerce_output_product_data_tabs’, 60 );

      For specific field

      add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );

      function woo_remove_product_tabs( $tabs ) {

      unset( $tabs[‘description’] ); // Remove the description tab
      unset( $tabs[‘reviews’] ); // Remove the reviews tab
      unset( $tabs[‘additional_information’] ); // Remove the additional information tab

      return $tabs;

      }
      put this code in fuctions.php file.