Search code examples
wordpressimagepluginsfile-typegetimagedata

How to insert image using wordpress and store it inside upload folder?


i tried file upload code but i am confuse where to place image name and that i have given inside input type file.

i comment out this code
// $file_name = pathinfo($tmp_name ,PATHINFO_FILENAME).time().".".pathinfo($tmp_name ,PATHINFO_EXTENSION);
// $file = $_FILES['your_meta_field']['tmp_name']['image'];

i am fresher at wordpress plugin development and this is new for me.

i seen soo many solution like there is function named wp_get_attachment_image located at plugin handbook.

with this code my insertion of image and other data is working successfully but image when i update then it says no image available i want my previous image name when i edit any post.

also it is not worked at fronend due to the reason of not properly image is stored.

i could not find my uploaded image inside upload folder.

here is my code :

<?php
/**
 * Plugin Name: Store Plugin 
 * Plugin URI: https://example.com/plugins/store-plugins/
 * Description: This is a description of my store plugin.
 * Version: 2.3.1
 * Author: Khushbu 
 * Author URI: https://example.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */
function db_active() {
  global $wpdb;
  $table = $wpdb->prefix . 'store_db'; 
  $charset_collate = $wpdb->get_charset_collate();
  $sql = "CREATE TABLE $table (
    store_id int(20) AUTO_INCREMENT PRIMARY KEY,
    store_name VARCHAR(255) NOT NULL,
    description TEXT NOT NULL,
    image VARCHAR(255) NOT NULL,
    address VARCHAR(255) NOT NULL,
    latitude VARCHAR(10) NOT NULL,
    longitude VARCHAR(10) NOT NULL
  ) $charset_collate;";  
  require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
  $result = dbDelta($sql);
}
register_activation_hook(__FILE__, 'db_active');

function db_deactive() {
  global $wpdb;
  $table = $wpdb->prefix . 'store_db'; 
  $sql = "DROP TABLE $table;";
  $wpdb->query($sql);
}
register_deactivation_hook(__FILE__, 'db_deactive');

function add_your_fields_meta_box() {
  add_meta_box(
    'your_custom_meta_box',          // ID of the meta box
    'Location Information',          // Title of the meta box
    'your_custom_meta_box_content',  // Callback function to generate the content
    'store_post',                     // Custom post type (your_post)
    'normal',                        // Placement - 'normal', 'advanced', 'side'
    'high'                           // Priority - 'high', 'core', 'default', 'low'
  );
}
add_action('add_meta_boxes', 'add_your_fields_meta_box');

function create_post_your_post() {
    register_post_type('store_post',
        array(
            'labels'       => array(
      'name'         => __('Store Post'),
            ),
            'public'       => true,
            'hierarchical' => true,
            'has_archive'  => true,
            'supports'     => array(
      'title',
      'editor',
      'excerpt',
      'thumbnail',
            ),
            'taxonomies'   => array(
      'post_tag',
      'category',
            )
        )
    );
    register_taxonomy_for_object_type('category', 'store_post');
    register_taxonomy_for_object_type('post_tag', 'store_post');
}

add_action('init', 'create_post_your_post');

function your_custom_meta_box_content($post) {
  $store_id = $post->ID;
  //$image = get_post_meta($store_id,'image',true);
  $image_id = get_post_meta($store_id, 'image_id', true);
  $address = get_post_meta($store_id, 'address', true);
  $latitude = get_post_meta($store_id, 'latitude', true);
  $longitude = get_post_meta($store_id, 'longitude', true);

  if ($image_id) {
    $image_src = wp_get_attachment_image_src($image_id, 'thumbnail');
    if ($image_src) {
      $image_url = $image_src[0];
    }
  }
  ?>      
  <b><label for="your_meta_field">Image:</label></b>
  <?php
  if (!empty($image_url)) {
    echo '<br><img src="' . esc_url($image_url) . '" style="max-width: 200px;" /><br>';
  }
  ?>
    <input type="file" name="your_meta_field[image]" id="your_meta_field[image]" onchange="previewImage(event)">
  <img id="image-preview" src="<?php echo esc_url($image_url); ?>" height="120" width="150"/>
  <?php
  if (!empty($image_url)) {
    echo '<br><small>chosen image: ' . esc_html($image_url) . '</small>';
  } ?> <br><br>


  <b><label for="your_meta_field">Address:</label></b>
  <textarea name="your_meta_field[address]" id="your_meta_field[address]" rows="3" cols="30" style="width:500px;"><?php echo esc_attr($address);?></textarea><br><br>

  <b><label for="your_meta_field">Latitude:</label></b>
  <input type="text" name="your_meta_field[latitude]" id="your_meta_field[latitude]" value="<?php echo esc_attr($latitude); ?>"><br><br>

  <b><label for="your_meta_field">Longitude:</label></b>
  <input type="text" name="your_meta_field[longitude]" id="your_meta_field[longitude]" value="<?php echo esc_attr($longitude); ?>"><br><br>

  <?php wp_nonce_field(basename(__FILE__), 'your_meta_box_nonce'); ?>
  <?php
}
function save_your_custom_meta_box_data($post_id) {
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return;
  }
  if (!isset($_POST['your_meta_box_nonce']) || !wp_verify_nonce($_POST['your_meta_box_nonce'], basename(__FILE__))) {
    return;
  }
  if ('store_post' !== get_post_type($post_id)) {
    return;
  }
  
  $meta_fields = isset($_POST['your_meta_field']) ? $_POST['your_meta_field'] : array();
  if (isset($_FILES['your_meta_field']['name']['image']) && !empty($_FILES['your_meta_field']['name']['image'])) 
  {
     $path_array = wp_upload_dir();
    // $file_name   =   pathinfo($tmp_name ,PATHINFO_FILENAME).time().".".pathinfo($tmp_name ,PATHINFO_EXTENSION);  
    // $file = $_FILES['your_meta_field']['tmp_name']['image'];
     $file_name = $_FILES['your_meta_field']['name']['image'];
     $file_type = $_FILES['your_meta_field']['type']['image'];

    if (strpos($file_type, 'image') !== false) 
    {
      $upload_overrides = array('test_form' => false);
      $uploaded_image = wp_handle_upload($_FILES['your_meta_field']['tmp_name']['image'], $upload_overrides);

      if ($uploaded_image && !isset($uploaded_image['error'])) 
      {
        // Delete previous image, if any
        $old_image_id = get_post_meta($post_id, 'image_id', true);
        if ($old_image_id) 
        {
          wp_delete_attachment($old_image_id, true);
        }
        // Save the uploaded image URL and ID in post meta
        update_post_meta($post_id, 'image', $uploaded_image['url']);
        update_post_meta($post_id, 'image_id', $uploaded_image['id']);
      } 
      else 
      {
        // Error handling if image upload fails
        $upload_error = $uploaded_image['error'] ?? 'Image upload failed.';
        wp_die($upload_error);
      }
    }
    else
    {
        // Error handling if the file is not an image
        wp_die('Please upload an image file.');
    }
  }
  if ( isset( $meta_fields['address'] ) )
  {
    update_post_meta( $post_id, 'address', sanitize_text_field( $meta_fields['address'] ) );  
  }
  if ( isset( $meta_fields['latitude'] ) )
  {
    update_post_meta( $post_id, 'latitude', sanitize_text_field( $meta_fields['latitude'] ) );  
  }
  if ( isset( $meta_fields['longitude'] ) ) {
    update_post_meta( $post_id, 'longitude', sanitize_text_field( $meta_fields['longitude'] ) );
  }

  if (isset($meta_fields['image']) && isset($meta_fields['address']) && isset($meta_fields['latitude']) && isset($meta_fields['longitude'])) {
    $store_name = get_the_title($post_id);
    $description = get_post_field('post_content', $post_id);
    $image = _sanitize_text_fields($meta_fields['image']);
    $address = sanitize_text_field($meta_fields['address']);
    $latitude = sanitize_text_field($meta_fields['latitude']);
    $longitude = sanitize_text_field($meta_fields['longitude']);

    global $wpdb;
    $table = $wpdb->prefix . 'store_db';
    $existing_record = $wpdb->get_row(
      $wpdb->prepare("SELECT * FROM $table WHERE store_id = %d", $post_id)
    );

    if ($existing_record) {
      // If a record exists, update the existing record
      $wpdb->update(
        $table,
        array(
          'store_name' => $store_name,
          'description' => $description,
          'image' => $image,
          'address' => $address,
          'latitude' => $latitude,
          'longitude' => $longitude,
        ),
        array('store_id' => $post_id),
        array('%s', '%s', '%s', '%s', '%s', '%s'),
        array('%d')
      );
    } else {
      // If no record exists, insert a new record
      $wpdb->insert(
        $table,
        array(
          'store_id' => $post_id,
          'store_name' => $store_name,
          'description' => $description,
          'image' => $image,
          'address' => $address,
          'latitude' => $latitude,
          'longitude' => $longitude,
        ),
        array('%d', '%s', '%s', '%s', '%s', '%s', '%s')
      );
    }
  }
}
add_action('save_post', 'save_your_custom_meta_box_data');
// my changes completed
?>
<script>
function previewImage(event) {
  var image = document.getElementById('image-preview');
  image.src = URL.createObjectURL(event.target.files[0]);
}
</script>

Solution

  • Please, try this solution:

    <?php
    /**
     * Plugin Name: Store Plugin
     * Plugin URI: https://example.com/plugins/store-plugins/
     * Description: This is a description of my store plugin.
     * Version: 2.3.1
     * Author: Khushbu
     * Author URI: https://example.com
     * License: GPL v2 or later
     * License URI: https://www.gnu.org/licenses/gpl-2.0.html
     */
    
    function db_active() {
        global $wpdb;
        $table = $wpdb->prefix . 'store_db';
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE $table (
        store_id int(20) AUTO_INCREMENT PRIMARY KEY,
        store_name VARCHAR(255) NOT NULL,
        description TEXT NOT NULL,
        image VARCHAR(255) NOT NULL,
        address VARCHAR(255) NOT NULL,
        latitude VARCHAR(10) NOT NULL,
        longitude VARCHAR(10) NOT NULL
      ) $charset_collate;";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $result = dbDelta($sql);
    }
    register_activation_hook(__FILE__, 'db_active');
    
    function db_deactive() {
        global $wpdb;
        $table = $wpdb->prefix . 'store_db';
        $sql = "DROP TABLE $table;";
        $wpdb->query($sql);
    }
    register_deactivation_hook(__FILE__, 'db_deactive');
    
    function add_your_fields_meta_box() {
        add_meta_box(
            'your_custom_meta_box',          // ID of the meta box
            'Location Information',          // Title of the meta box
            'your_custom_meta_box_content',  // Callback function to generate the content
            'store_post',                     // Custom post type (your_post)
            'normal',                        // Placement - 'normal', 'advanced', 'side'
            'high'                           // Priority - 'high', 'core', 'default', 'low'
        );
    }
    add_action('add_meta_boxes', 'add_your_fields_meta_box');
    
    function create_post_your_post() {
        register_post_type('store_post',
            array(
                'labels'       => array(
                    'name'         => __('Store Post'),
                ),
                'public'       => true,
                'hierarchical' => true,
                'has_archive'  => true,
                'supports'     => array(
                    'title',
                    'editor',
                    'excerpt',
                    'thumbnail',
                ),
                'taxonomies'   => array(
                    'post_tag',
                    'category',
                )
            )
        );
        register_taxonomy_for_object_type('category', 'store_post');
        register_taxonomy_for_object_type('post_tag', 'store_post');
    }
    
    add_action('init', 'create_post_your_post');
    
    add_action( 'post_edit_form_tag', function() {
        echo ' enctype="multipart/form-data"';
    } );
    
    function your_custom_meta_box_content($post) {
        $store_id = $post->ID;
    
        //$image = get_post_meta($store_id,'image',true);
        $image_id = get_post_meta($store_id, 'image_id', true);
        $address = get_post_meta($store_id, 'address', true);
        $latitude = get_post_meta($store_id, 'latitude', true);
        $longitude = get_post_meta($store_id, 'longitude', true);
    
        $default_url = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
        $image_url = '';
        if ($image_id) {
            $image_src = wp_get_attachment_image_src($image_id, 'thumbnail');
            if ($image_src) {
                $image_url = $image_src[0];
                $image_url = esc_url($image_url);
            }
        }
        ?>
        <b><label for="your_meta_field">Image:</label></b>
        <?php
        if (!empty($image_url)) {
            echo '<br><img src="' . esc_url($image_url) . '" style="max-width: 200px;" /><br>';
        }
        ?>
        <script>
            function previewImage(event) {
                var image = document.getElementById('image-preview');
                image.src = URL.createObjectURL(event.target.files[0]);
            }
        </script>
        <input type="file" name="image" id="your_meta_field[image]" onchange="previewImage(event)">
        <img id="image-preview" src="<?php echo !empty($image_url) ? $image_url : $default_url; ?>" height="120" width="150"/>
        <?php
        if (!empty($image_url)) {
            echo '<br><small>chosen image: ' . esc_html($image_url) . '</small>';
        } ?> <br><br>
    
    
        <b><label for="your_meta_field[image]">Address:</label></b>
        <textarea name="your_meta_field[address]" id="your_meta_field[address]" rows="3" cols="30" style="width:500px;"><?php echo esc_attr($address);?></textarea><br><br>
    
        <b><label for="your_meta_field">Latitude:</label></b>
        <input type="text" name="your_meta_field[latitude]" id="your_meta_field[latitude]" value="<?php echo esc_attr($latitude); ?>"><br><br>
    
        <b><label for="your_meta_field">Longitude:</label></b>
        <input type="text" name="your_meta_field[longitude]" id="your_meta_field[longitude]" value="<?php echo esc_attr($longitude); ?>"><br><br>
    
        <?php wp_nonce_field(basename(__FILE__), 'your_meta_box_nonce'); ?>
        <?php
    }
    function save_your_custom_meta_box_data($post_id) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (!isset($_POST['your_meta_box_nonce']) || !wp_verify_nonce($_POST['your_meta_box_nonce'], basename(__FILE__))) {
            return;
        }
        if ('store_post' !== get_post_type($post_id)) {
            return;
        }
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
    
        $meta_fields = isset($_POST['your_meta_field']) ? $_POST['your_meta_field'] : array();
        if (isset($_FILES['image']))
        {
            $wp_upload_dir = wp_upload_dir();
            $file_type = $_FILES['image']['type'];
    
            if (strpos($file_type, 'image') !== false)
            {
                $uploaded_image = wp_handle_upload($_FILES['image'], ['test_form' => false]);
    
                if ($uploaded_image && empty($uploaded_image['error']))
                {
                    // Delete previous image, if any
                    $old_image_id = get_post_meta($post_id, 'image_id', true);
                    if ($old_image_id)
                    {
                        wp_delete_attachment($old_image_id, true);
                    }
                    // Save the uploaded image URL and ID in post meta
                    update_post_meta($post_id, 'image', $uploaded_image['url']);
    
                    $attachment = array(
                        'guid'           => $wp_upload_dir['url'] . '/' . basename( $uploaded_image['file'] ),
                        'post_mime_type' => $uploaded_image['type'],
                        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $uploaded_image['file'] ) ),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );
    
                    $attach_id = wp_insert_attachment( $attachment, $uploaded_image['file'], $post_id );
                    $attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_image['file'] );
                    wp_update_attachment_metadata( $attach_id, $attach_data );
                    update_post_meta($post_id, 'image_id', $attach_id);
    
                }
                else
                {
                    // Error handling if image upload fails
                    $upload_error = $uploaded_image['error'] ?? 'Image upload failed.';
                    wp_die($upload_error);
                }
            }
            else
            {
                // Error handling if the file is not an image
                wp_die('Please upload an image file.');
            }
        }
        if ( isset( $meta_fields['address'] ) )
        {
            update_post_meta( $post_id, 'address', sanitize_text_field( $meta_fields['address'] ) );
        }
        if ( isset( $meta_fields['latitude'] ) )
        {
            update_post_meta( $post_id, 'latitude', sanitize_text_field( $meta_fields['latitude'] ) );
        }
        if ( isset( $meta_fields['longitude'] ) ) {
            update_post_meta( $post_id, 'longitude', sanitize_text_field( $meta_fields['longitude'] ) );
        }
    
        if (isset($meta_fields['image']) && isset($meta_fields['address']) && isset($meta_fields['latitude']) && isset($meta_fields['longitude'])) {
            $store_name = get_the_title($post_id);
            $description = get_post_field('post_content', $post_id);
            $image = _sanitize_text_fields($meta_fields['image']);
            $address = sanitize_text_field($meta_fields['address']);
            $latitude = sanitize_text_field($meta_fields['latitude']);
            $longitude = sanitize_text_field($meta_fields['longitude']);
    
            global $wpdb;
            $table = $wpdb->prefix . 'store_db';
            $existing_record = $wpdb->get_row(
                $wpdb->prepare("SELECT * FROM $table WHERE store_id = %d", $post_id)
            );
    
            if ($existing_record) {
                // If a record exists, update the existing record
                $wpdb->update(
                    $table,
                    array(
                        'store_name' => $store_name,
                        'description' => $description,
                        'image' => $image,
                        'address' => $address,
                        'latitude' => $latitude,
                        'longitude' => $longitude,
                    ),
                    array('store_id' => $post_id),
                    array('%s', '%s', '%s', '%s', '%s', '%s'),
                    array('%d')
                );
            } else {
                // If no record exists, insert a new record
                $wpdb->insert(
                    $table,
                    array(
                        'store_id' => $post_id,
                        'store_name' => $store_name,
                        'description' => $description,
                        'image' => $image,
                        'address' => $address,
                        'latitude' => $latitude,
                        'longitude' => $longitude,
                    ),
                    array('%d', '%s', '%s', '%s', '%s', '%s', '%s')
                );
            }
        }
    }
    add_action('save_post', 'save_your_custom_meta_box_data');