How to Retrieve a list of database table names for WordPress Database

If you ever need to grab a list of tables for whatever reason for the current WordPress database, here is how you can do so.

The official WordPress way is to use: wpdb

global $wpdb;
print_r( $wpdb->tables() );

You can read up about this in the WordPress documentation:

wpdb::tables()

This can be used with Parameters

$scope
(string) (Optional) Possible values include 'all', 'global', 'ms_global', 'blog', or 'old' tables.

Default value: 'all'

$prefix
(bool) (Optional) Whether to include table prefixes. If blog prefix is requested, then the custom users and usermeta tables will be mapped.

Default value: true

$blog_id
(int) (Optional) The blog_id to prefix. Used only when prefix is requested. Defaults to wpdb::$blogid.

But This will only return the WordPress default tables, excluding any other tables that were created by plugins or theme. This will give you a list of all the defualt tables.

Get All Tables

Including custom tables created by plugins and themes.

Let’s try to get all the tables including the custom database tables that plugins or themes may have created, To achieve this we can do a simple SQL query.

I’m going to use a simple class, but you can also just use a function or whatever other method you prefer depending on your use case.

The Class will only have two static methods, one to run the query and retrieve the tables. The second method will handle preparing the tables array list for output.

Method #1

	/**
	 * Get wp database tables.
	 *
	 * @return object
	 */
	protected static function tables() {
		global $wpdb;
		return $wpdb->get_results(
			$wpdb->prepare( "SHOW TABLES" )
		);
	}

Method #2

	/**
	 * Get the tables list.
	 *
	 * @return array.
	 */
	public static function table_list() {
		foreach ( self::tables() as $get_tables ) {
			foreach ( $get_tables as $table ) {
				$list[] = $table;
			}
		}
		return $list;
	}

The complete class

Now we can simply do:

print_r( WPTable::table_list() );