Reputation: 43
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>
Upvotes: 0
Views: 579
Reputation: 43
Here is my complete code: store-plugin.php
<?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,
image_id INT,
image_name VARCHAR(255),
description TEXT 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 custom_upload_dir($upload_dir)
{
$c_year = date('Y');
$c_month = date('m');
$upload_path = $upload_dir['basedir'] . '/' . $c_year . '/' . $c_month;
$upload_url = $upload_dir['baseurl'] . '/' . $c_year . '/' . $c_month;
$upload_dir['path'] = $upload_path;
$upload_dir['url'] = $upload_url;
return $upload_dir;
}
add_filter('upload_dir', 'custom_upload_dir');
function your_custom_meta_box_content($post)
{
$store_id = $post->ID;
$image_id = get_post_meta($store_id, 'image_id', true);
$image_name = get_post_meta($store_id, 'image_name', 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);
$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) . '" id="image-preview" style="max-width: 100px;" /><br>';
}
?>
<input type="button" id="upload_button" class="button" value="Select Image">
<input type="button" id="remove_button" class="button" value="Remove Image">
<input type="hidden" name="your_meta_field[image_id]" id="your_meta_field[image_id]" value="<?php echo esc_attr($image_id); ?>">
<input type="hidden" name="your_meta_field[image_name]" id="your_meta_field[image_name]" value="<?php echo esc_attr($image_name); ?>">
<br><br>
<b><label for="your_meta_field[address]">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]">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]">Longitude:</label></b>
<input type="text" name="your_meta_field[longitude]" id="your_meta_field[longitude]" value="<?php echo esc_attr($longitude); ?>"><br><br>
<script>
jQuery(document).ready(function ($) {
var filee;
function openMediaUploader() {
if (filee) {
filee.open();
return;
}
filee = wp.media.frames.filee = wp.media({
title: 'Select Image',
button: {
text: 'Choose Image',
},
multiple: false,
});
filee.on('select', function () {
var attachment = filee.state().get('selection').first().toJSON();
console.log(attachment);
$('#your_meta_field\\[image_id\\]').val(attachment.id);
$('#your_meta_field\\[image_name\\]').val(attachment.filename);
$('#image-preview').attr('src', attachment.url);
});
filee.open();
}
$(document).on('click', '#upload_button', function (event) {
event.preventDefault();
openMediaUploader();
});
var imageId = $('#your_meta_field\\[image_id\\]').val();
var imageFilename = $('#your_meta_field\\[image_name\\]').val();
if (imageId && imageFilename) {
var imageSrc = wp.media.attachment(imageId).get('url');
$('#image-preview').attr('src', imageSrc);
}
$(document).on('click', '#remove_button', function (event) {
event.preventDefault();
$('#your_meta_field\\[image_id\\]').val(''); // Clear the image ID field
$('#your_meta_field\\[image_name\\]').val(''); // Clear the image name field
$('#image-preview').attr('src', '');
});
});
</script>
<?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();
$image_name = isset($meta_fields['image_name']) ? sanitize_text_field($meta_fields['image_name']) : '';
update_post_meta($post_id, 'image_name', $image_name);
if (!empty($_FILES['your_meta_field']['name']['image_name'])) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$uploaded_file = wp_handle_upload($_FILES['your_meta_field']['name']['image_name'], array('test_form' => false));
if ($uploaded_file && !isset($uploaded_file['error'])) {
$image_name = sanitize_file_name(basename($uploaded_file['file']));
update_post_meta($post_id, 'image_name', $image_name);
$attachment_id = wp_insert_attachment(array(
'post_mime_type' => $uploaded_file['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($uploaded_file['file'])),
'post_content' => '',
'post_status' => 'inherit'
), $uploaded_file['file'], $post_id);
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $uploaded_file['file']);
wp_update_attachment_metadata($attachment_id, $attachment_data);
}
$image_url = wp_get_attachment_url($attachment_id);
if ($image_url) {
$image_name = $image_url;
update_post_meta($post_id, 'image_name', $image_name);
}
update_post_meta($post_id, 'image_id', $attachment_id);
}
} else {
$image_id = absint($meta_fields['image_id']);
update_post_meta($post_id, 'image_id', $image_id);
$existing_image_url = wp_get_attachment_url($image_id);
if ($existing_image_url) {
$image_name = $existing_image_url;
update_post_meta($post_id, 'image_name', $image_name);
}
}
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']));
}
$store_name = get_the_title($post_id);
$description = get_post_field('post_content', $post_id);
$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) {
$wpdb->update(
$table,
array(
'store_name' => $store_name,
'image_name' => $image_name,
'description' => $description,
'address' => $address,
'latitude' => $latitude,
'longitude' => $longitude,
),
array('store_id' => $post_id),
array('%s', '%s', '%s', '%s', '%s', '%s'),
array('%d')
);
} else {
$wpdb->insert(
$table,
array(
'store_id' => $post_id,
'store_name' => $store_name,
'image_name' => $image_name,
'description' => $description,
'address' => $address,
'latitude' => $latitude,
'longitude' => $longitude,
),
array('%d', '%s', '%s', '%s', '%s', '%s', '%s')
);
}
}
add_action('save_post', 'save_your_custom_meta_box_data');
?>
single-store.php
<?php
while (have_posts()) : the_post();
the_title('<h1>', '</h1>');
the_content();
$store_id = get_the_ID();
$image_id = get_post_meta($store_id, 'image_id', true);
$image_name = get_post_meta($store_id, 'image_name', 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];
}
}
?>
<div class="store-location-info">
<?php if (!empty($image_url)) : ?>
<img src="<?php echo esc_url($image_url); ?>" alt="<?php the_title_attribute(); ?>" style="max-width: 200px;">
<?php endif; ?>
<?php if (!empty($image_name)) : ?>
<p><strong>Image Name:</strong> <?php echo esc_html($image_name); ?></p>
<?php endif; ?>
<p><strong>Address:</strong> <?php echo esc_html($address); ?></p>
<p><strong>Latitude:</strong> <?php echo esc_html($latitude); ?></p>
<p><strong>Longitude:</strong> <?php echo esc_html($longitude); ?></p>
</div>
<?php
endwhile;
?>
template-location-records.php
<?php
get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
$args = array(
'post_type' => 'store_post',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
if ($query->have_posts()) :
?>
<table class="store-locations-table">
<thead>
<tr>
<th>Store Name</th>
<th>Description</th>
<th>Image</th>
<th>Address</th>
<th>Latitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody>
<?php
while ($query->have_posts()) : $query->the_post();
$store_name = get_the_title();
$description = get_the_content();
$image_id = get_post_meta(get_the_ID(), 'image_id', true);
$address = get_post_meta(get_the_ID(), 'address', true);
$latitude = get_post_meta(get_the_ID(), 'latitude', true);
$longitude = get_post_meta(get_the_ID(), 'longitude', true);
$image_url = '';
if ($image_id) {
$image_src = wp_get_attachment_image_src($image_id, 'thumbnail');
if ($image_src) {
$image_url = $image_src[0];
}
}
?>
<tr>
<td><?php echo esc_html($store_name); ?></td>
<td><?php echo esc_html($description); ?></td>
<td>
<?php if (!empty($image_url)) : ?>
<img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($store_name); ?>" style="max-width: 100px;">
<?php else : ?>
<p>No image available</p>
<?php endif; ?>
</td>
<td><?php echo esc_html($address); ?></td>
<td><?php echo esc_html($latitude); ?></td>
<td><?php echo esc_html($longitude); ?></td>
</tr>
<?php
endwhile;
?>
</tbody>
</table>
<?php
else :
echo '<p>No location records found.</p>';
endif;
wp_reset_postdata();
?>
</main>
</div>
<?php
get_footer();
?>
functions.php
//my-location function
function display_location_info_shortcode() {
ob_start();
if (have_posts()) {
while (have_posts()) : the_post();
$store_id = get_the_ID();
$image_id = get_post_meta($store_id, 'image_id', true);
$image_name = get_post_meta($store_id, 'image_name', 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);
$image_url = '';
if ($image_id) {
$image_src = wp_get_attachment_image_src($image_id, 'thumbnail');
if ($image_src) {
$image_url = $image_src[0];
}
}
?>
<div class="store-location-info">
<?php if (!empty($image_url)) : ?>
<img src="<?php echo esc_url($image_url); ?>" alt="<?php the_title_attribute(); ?>" style="max-width: 200px;">
<?php endif; ?>
<?php if (!empty($image_name)) : ?>
<p><strong>Image Path:</strong> <?php echo esc_html($image_name); ?></p>
<?php endif; ?>
<p><strong>Address:</strong> <?php echo esc_html($address); ?></p>
<p><strong>Latitude:</strong> <?php echo esc_html($latitude); ?></p>
<p><strong>Longitude:</strong> <?php echo esc_html($longitude); ?></p>
</div>
<?php
endwhile;
} else {
echo '<p>No location records found.</p>';
}
return ob_get_clean();
}
add_shortcode('display_location_info', 'display_location_info_shortcode');
Thank you :)
Upvotes: 0
Reputation: 43
i got my answer that works well as database insertion, frontend that i have coded and backend working well.
here is my updated 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');
add_action( 'post_edit_form_tag', function() {
echo ' enctype="multipart/form-data"';
} );
function your_custom_meta_box_content($post) {
$store_id = $post->ID;
$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'])) {
$old_image_id = get_post_meta($post_id, 'image_id', true);
if ($old_image_id) {
wp_delete_attachment($old_image_id, true);
}
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 {
$upload_error = $uploaded_image['error'] ?? 'Image upload failed.';
wp_die($upload_error);
}
} else {
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']));
}
$store_name = get_the_title($post_id);
$description = get_post_field('post_content', $post_id);
$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) {
$wpdb->update(
$table,
array(
'store_name' => $store_name,
'description' => $description,
'address' => $address,
'latitude' => $latitude,
'longitude' => $longitude,
),
array('store_id' => $post_id),
array('%s', '%s', '%s', '%s', '%s'),
array('%d')
);
} else {
$wpdb->insert(
$table,
array(
'store_id' => $post_id,
'store_name' => $store_name,
'description' => $description,
'address' => $address,
'latitude' => $latitude,
'longitude' => $longitude,
),
array('%d', '%s', '%s', '%s', '%s', '%s')
);
}
}
add_action('save_post', 'save_your_custom_meta_box_data');
?>
Upvotes: 0
Reputation: 419
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');
Upvotes: 1