wpdb::set_prefix() WordPress Method

The wpdb::set_prefix() method allows you to set a new table prefix for WordPress tables. This is useful if you need to run multiple WordPress installations in a single database.

wpdb::set_prefix( string $prefix, bool $set_table_names = true ) #

Sets the table prefix for the WordPress tables.


Parameters

$prefix

(string)(Required)Alphanumeric name for the new prefix.

$set_table_names

(bool)(Optional) Whether the table names, e.g. wpdb::$posts, should be updated or not.

Default value: true


Top ↑

Return

(string|WP_Error) Old prefix or WP_Error on error.


Top ↑

Source

File: wp-includes/wp-db.php

	public function set_prefix( $prefix, $set_table_names = true ) {

		if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) {
			return new WP_Error( 'invalid_db_prefix', 'Invalid database prefix' );
		}

		$old_prefix = is_multisite() ? '' : $prefix;

		if ( isset( $this->base_prefix ) ) {
			$old_prefix = $this->base_prefix;
		}

		$this->base_prefix = $prefix;

		if ( $set_table_names ) {
			foreach ( $this->tables( 'global' ) as $table => $prefixed_table ) {
				$this->$table = $prefixed_table;
			}

			if ( is_multisite() && empty( $this->blogid ) ) {
				return $old_prefix;
			}

			$this->prefix = $this->get_blog_prefix();

			foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
				$this->$table = $prefixed_table;
			}

			foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
				$this->$table = $prefixed_table;
			}
		}
		return $old_prefix;
	}


Top ↑

Changelog

Changelog
VersionDescription
2.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.