如何使用wordpress插入图片并将其存储在上传文件夹中?

问题描述 投票:0回答:0

我尝试了文件上传代码,但我很困惑在哪里放置图像名称以及我在输入类型文件中给出的位置。

我注释掉这段代码
// $file_name = pathinfo($tmp_name ,PATHINFO_FILENAME).time().".".pathinfo($tmp_name ,PATHINFO_EXTENSION);
// $file = $_FILES['your_meta_field']['tmp_name']['image'];

我对 WordPress 插件开发比较陌生,这对我来说是新的。

我看到了很多解决方案,比如插件手册中有一个名为 wp_get_attachment_image 的函数。

使用此代码,我插入的图像和其他数据工作正常,但是当我更新图像时,它说没有可用的图像,当我编辑任何帖子时,我想要我以前的图像名称。

由于图像存储不正确,它在前端也不起作用。

我在上传文件夹中找不到我上传的图片。

这是我的代码:

<?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>
wordpress image plugins file-type getimagedata
© www.soinside.com 2019 - 2024. All rights reserved.