wpdb::get_blog_prefix( int $blog_id = null ): string

Gets blog prefix.

Parameters

$blog_idintoptional
Blog ID to retrieve the table prefix for.
Defaults to the current blog ID.

Default:null

Return

string Blog prefix.

Source

public function get_blog_prefix( $blog_id = null ) {
	if ( is_multisite() ) {
		if ( null === $blog_id ) {
			$blog_id = $this->blogid;
		}

		$blog_id = (int) $blog_id;

		if ( defined( 'MULTISITE' ) && ( 0 === $blog_id || 1 === $blog_id ) ) {
			return $this->base_prefix;
		} else {
			return $this->base_prefix . $blog_id . '_';
		}
	} else {
		return $this->base_prefix;
	}
}

Changelog

VersionDescription
3.0.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Create a table while installing the plugin. Get the database table prefix with $wpdb->get_blog_prefix();

    register_activation_hook( __FILE__, 'myplugin_activation' );
    function myplugin_activation() {
    	// Get access to global database access class
    	global $wpdb;
    	// Create table on main blog in network mode or single blog
    	myplugin_create_table( $wpdb->get_blog_prefix() );
    }
    
    function myplugin_create_table( $prefix ) {
    	// Prepare SQL query to create database table
    	// using function parameter
    	$creation_query =
    	'CREATE TABLE IF NOT EXISTS ' . $prefix . 'myplugin_bug_data (
    	`bug_id` int(20) NOT NULL AUTO_INCREMENT,
    	`bug_description` text,
    	`bug_version` varchar(10) DEFAULT NULL,
    	`bug_report_date` date DEFAULT NULL,
    	`bug_status` int(3) NOT NULL DEFAULT 0,
    	PRIMARY KEY (`bug_id`)
    	);';
    	global $wpdb;
    	$wpdb->query( $creation_query );
    }

You must log in before being able to contribute a note or feedback.