Skip to content
Advertisement

How to create custom tables in WordPress using my own plugin?

I am new in WordPress plugin development. This is my core PHP and HTML code

create-table.html

  <form method="post" action="function.php">
    <input type="text" name="table_name">
    <input type="submit" name="create">
    </form>

function.php

if(isset($_POST['create'])
{
$table-name=$_POST['table_name'];

//create table query here

header("location: add_table_attribute.php");
}

I want to use this same process in my WordPress plugin development. Please any one help me.

Thanks in advance.

Advertisement

Answer

You have very many options for that.

Here is one of them as a little plugin. I’ve commented it for you: https://hostr.co/pRBSmTkZ2LlJ

<?php
    /*
        Plugin Name:    stackoverlow - My own Table
        Version:        1.0.0
    */

    class My_Table {

        /*
            Add an menu entry in the Administration. Fore more information see: http://codex.wordpress.org/Administration_Menus
        */
        public function __construct() {
            add_action('admin_menu',    array($this, 'admin_menu'));
        }

        public function admin_menu() {
            $menu_title = 'Table: Title of your Menu';  // The title of your menu entry
            $menu_slug  = 'my_table';                   // The slug, for example: wp-admin/admin.php?page=my_table
            add_menu_page($menu_title, $menu_title, 'manage_options', $menu_slug, array($this, 'admin_page'));
        }

        /*
            Here is the Output of your Page
        */
        public function admin_page() {
            global $wpdb;

            // Handle here your Data
            if(isset($_POST['create'])) {
                $table_name = $_POST['table_name'];

                // WARNING: SQL Injections - Data not prepared!
                $wpdb->query("CREATE TABLE IF NOT EXISTS `" . $table_name . "`;");
            }

            if(!empty($wpdb->last_error)) {
                printf('<pre>ERROR: %s</pre>', $wpdb->last_error);
            }

            if(!empty($wpdb->last_query)) {
                printf('<pre>Query: %s</pre>', $wpdb->last_query);
            }
            ?>
            <form method="post" action="<?php print admin_url('admin.php?page=my_table'); ?>">
                <input type="text" name="table_name" />
                <input type="submit" name="create" />
            </form>
            <?php
        }
    }

    new My_Table();
?>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement