php wordpress custom_post_type插入数据到现有表wp_posts

kr98yfug  于 2023-08-02  发布在  PHP
关注(0)|答案(1)|浏览(86)

我已经创建了一个插件,适用于现有的表wp_posts内的WordPress数据库.为此,我已经创建了插件的代码,添加3个字段到现有的数据库时,当激活插件,也从现有的数据库中删除3个字段时,停用插件。
this is screenshot of my layout
我想当我点击更新后,在字段中添加值,然后地址,纬度和经度字段显示该数据到数据库。
代码如下:

<?php
/**
 * Plugin Name: Hello World
 * Plugin URI: https://example.com/my-plugin
 * Description: This is a description of my hello world sample plugin.
 * Version: 2.3.1
 * Author: Selin
 * Author URI: https://example.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */
include_once WP_PLUGIN_DIR . '/form-data/connection.php';
include_once(__DIR__. '\Admin\Store\createfile.php');
include_once(__DIR__ . '\Admin\Store\view.php');
//global $post;

function db_activate() {
  global $wpdb;
  $table = $wpdb->prefix . 'posts'; 
  $charset_collate = $wpdb->get_charset_collate();
  $sql = "ALTER TABLE $table
      ADD `address` VARCHAR(255) NOT NULL,
      ADD `longitude` VARCHAR(20) NOT NULL,
      ADD `latitude` VARCHAR(20) NOT NULL
  ;";
  $wpdb->query($sql);
  $wpdb->get_results("DESCRIBE $table");
}
register_activation_hook(__FILE__, 'db_activate');

function db_deactivate() {
    global $wpdb;
    $table = $wpdb->prefix . 'posts';
    $sql = "ALTER TABLE $table DROP COLUMN `address`, DROP COLUMN `longitude`, DROP COLUMN `latitude`";
    $wpdb->query($sql);
}
register_deactivation_hook(__FILE__, 'db_deactivate');

// custom-post-type
function custom_store_metaboxes() {
  add_meta_box(
      'store_location',
      'Store Location',
      'display_store',
      'store',
      'normal',
      'high'
  );
}

function display_store($post) {
  // Get existing address, latitude, and longitude values (if any)
  $address = get_post_meta($post->ID, 'address', true);
  $latitude = get_post_meta($post->ID, 'latitude', true);
  $longitude = get_post_meta($post->ID, 'longitude', true);
  ?>
  <label for="address">Address:</label><br>
  <input type="text" id="address" name="address" value="<?php echo esc_attr($address); ?>"/><br><br>

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

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

function save_store_location_fields($post_id) {
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return;
  }

  if (!current_user_can('edit_post', $post_id)) {
      return;
  }
    // Insert or update the address
  if (isset($_POST['address'])) {
    update_post_meta($post_id, 'address', sanitize_text_field($_POST['address']));
  }

  // Insert or update the latitude
  if (isset($_POST['latitude'])) {
      update_post_meta($post_id, 'latitude', sanitize_text_field($_POST['latitude']));
  }

  // Insert or update the longitude
  if (isset($_POST['longitude'])) {
      update_post_meta($post_id, 'longitude', sanitize_text_field($_POST['longitude']));
  }  
}
add_action('save_post_store', 'save_store_location_fields');

//wp_insert_post($address,$latitude,$longitude);
add_action('add_meta_boxes_store', 'custom_store_metaboxes');
//add_action('save_post_store', 'save_store_location_fields');

function register_custom_store_post_type() {
    $labels = array(
        'name'                  => _x( 'Store Locator', 'Post type general name', 'textdomain' ),
        'singular_name'         => _x( 'Store', 'Post type singular name', 'textdomain' ),
        'menu_name'             => _x( 'Stores', 'Admin Menu text', 'textdomain' ),
        'name_admin_bar'        => _x( 'Store', 'Add New on Toolbar', 'textdomain' ),
        'add_new'               => __( 'Add New', 'textdomain' ),
        'add_new_item'          => __( 'Add New Store', 'textdomain' ),
        'new_item'              => __( 'New Store', 'textdomain' ),
        'edit_item'             => __( 'Edit Store', 'textdomain' ),
        'view_item'             => __( 'View Store', 'textdomain' ),
        'all_items'             => __( 'All Stores', 'textdomain' ),
        'search_items'          => __( 'Search Stores', 'textdomain' ),
        'parent_item_colon'     => __( 'Parent Stores:', 'textdomain' ),
        'not_found'             => __( 'No stores found.', 'textdomain' ),
        'not_found_in_trash'    => __( 'No stores found in Trash.', 'textdomain' ),
        'featured_image'        => _x( 'Store Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'set_featured_image'    => _x( 'Set cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'remove_featured_image' => _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'use_featured_image'    => _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'archives'              => _x( 'Store archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'textdomain' ),
        'insert_into_item'      => _x( 'Insert into store', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'textdomain' ),
        'uploaded_to_this_item' => _x( 'Uploaded to this store', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'textdomain' ),
        'filter_items_list'     => _x( 'Filter stores list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'textdomain' ),
        'items_list_navigation' => _x( 'Stores list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'textdomain' ),
        'items_list'            => _x( 'Stores list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ),
    );

    $args = array(
        'labels'             => $labels,
        'description'        => 'Store custom post type.',
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'store' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 10,
        'supports'           => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
        'menu_icon'          => 'dashicons-location', 
        'show_in_rest'       => true,
        'register_meta_box_cb' => 'custom_store_metaboxes'
    );  
    register_post_type('store', $args);
}
add_action('init', 'register_custom_store_post_type');
?>

字符串
我想插入记录在该领域的地址,纬度和经度请帮助我与此代码

这里是我的更新代码,根据您的评论和回复,我已经创建了我的新表:

<?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');

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);
  $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>
  <?php
  if (!empty($image)) {
    echo '<br><img src="' . esc_url($image) . '" style="max-width: 200px;" /><br>';
  }
  ?>
  <input type="file" name="your_meta_field[image]" id="your_meta_field[image]">
  <?php
  // Check if there's a previously saved image URL and display it in the file input field
  if (!empty($image)) {
    echo '<br><small>Previously chosen image: ' . esc_html($image) . '</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_url = media_handle_upload('your_meta_field', $post_id);
      if (!is_wp_error($image_url)) {
        update_post_meta($post_id, 'image', $image_url);
    }
 }
  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
?>

2jcobegt

2jcobegt1#

我的天啊警钟在我的脑海里响个不停。请不要向核心表中添加列。为什么不呢?

  • 核心版本更新(例如,即将发布的6.2.2到6.3更新)具有将核心表的结构恢复为标准结构的过程。要么核心更新失败,要么它将有助于删除额外的列。
  • Core有一个缓存子系统,用于处理像wp_postmeta表中的元数据。您也可以利用这一点并获得性能优势。
  • WordPress的生态系统中充满了使用这些表的代码(核心、插件、主题)。例如,在插件库中有成千上万个插件。除了 * 它能工作吗?* 您会遇到这样的代码,它假定自己知道posts表中有哪些列,并且如果存在其他列,则会执行一些奇怪的操作。我只是想礼貌点。事实是,WordPress生态系统包含了很多基本上能正常工作的坏代码。您正在通过向核心表中添加列这样奇怪的操作,诱使那些糟糕的代码咬您一口。

有人在评论中指出,wp_postmeta表是放置数据的地方。这是正确的。您已经在使用update_post_meta()来完成这一操作,基本上是正确的。
顺便说一下,WordPress插件的惯例是在 * 删除 * 插件时删除额外的数据,而不是在 * 停用 * 插件时删除。

相关问题