2

I am looking for how to add images in a custom database table using WordPress code

I am new in WordPress plugin development. I've created code for a plugin named store plugin. I've taken fields like store_id, store_name, description, image, address, latitude and longitude.

I have successfully inserted other data into my store_db database.

Please help me with how to add an image and also I have a query on that my data is also inserted into the wp_posts table default

I've my own table that is inserting data successfully but I don't want to store my records at the posts table.

Here is my code:

<?php
/**
 * Plugin Name: Store Plugin 
 * Plugin URI: https://example.com/my-plugin
 * Description: This is a description of my hello world sample 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');

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);
  $address = get_post_meta($store_id, 'address', true);
  $latitude = get_post_meta($store_id, 'latitude', true);
  $longitude = get_post_meta($store_id, 'longitude', true);
  ?>  
  <b><label for="your-meta-field">Image:</label></b>
  <input type="file" name="your_meta_field[image]" id="your_meta_field[image]" value="<?php echo esc_attr($image); ?>"><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 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'
  );
}

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($meta_fields['image'])){
    update_post_meta($post_id,'image',sanitize_text_field($meta_fields['image']));
  }
  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
?>
5
  • 1
    One clarification, you said you need these fields: store_id, store_name, description, image, address, latitude and longitude Now, is your wordpress installation a single "store" (in which case you need to set values for the fields just once), or are you handling "multiple stores" in your wordpress installation (in which case you need to set the values multiple times, one for each store)? Commented Jul 29, 2023 at 11:29
  • @GrafiCode no it's now just a single store. Commented Jul 31, 2023 at 8:41
  • 1
    ok, I understand now why you don't need actual posts, you actually need some sort of configuration page in the backend where you can set those values (and access them sitewide). This guide on wordpress tells you how to create an option page: codex.wordpress.org/Creating_Options_Pages Commented Jul 31, 2023 at 10:05
  • 1
    I must say, in my experience when I have to handle custom post types or option pages on wordpress, I personally rely on the PODS framework (pods.io). It's a plugin for developers, it lets you create custom posts, custom taxonomies and custom option pages directly from the backend interface. Commented Jul 31, 2023 at 10:07
  • @GrafiCode okay thank you very much for suggesting this page. i used classic editor and below that i've added custom post type and created this mentioned fields. i also get trubble with saving my data in store_db and also my data is default storing in wp_posts table. Commented Aug 1, 2023 at 6:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.