作为对@Marcus Downing answer的补充,我添加了一个保护,以防止在删除MU站点时删除表。
这旨在用作mu插件。如果要在其他地方使用,请更改;muplugins\\u已加载“;挂钩到“;已加载插件;。
<?php
/**
* Plugin name: Shared Taxonomies for Multi-site
* Version: 0.1
* Plugin Author: Marcus Downing, Lucas Bustamante
* Author URI: https://wordpress.stackexchange.com/a/386318/27278
* Description: All instances of multi-site share the same taxonomies as the main site of the network.
*/
$sharedTaxonomies = new SharedTaxonomies;
add_action(\'muplugins_loaded\', [$sharedTaxonomies, \'shareTaxonomies\'], 1, 0);
add_action(\'switch_blog\', [$sharedTaxonomies, \'shareTaxonomies\'], 1, 0);
add_filter(\'wpmu_drop_tables\', [$sharedTaxonomies, \'protectGlobalTables\'], 1, 2);
class SharedTaxonomies
{
/**
* Multi-sites uses term tables from the main site.
*/
public function shareTaxonomies()
{
/**
* @var wpdb $wpdb
* @var WP_Object_Cache $wp_object_cache
*/
global $wpdb, $wp_object_cache;
$wpdb->terms = $wpdb->base_prefix . \'terms\';
$wpdb->term_taxonomy = $wpdb->base_prefix . \'term_taxonomy\';
$wpdb->flush();
$wp_object_cache->flush();
}
/**
* Prevent global tables from being deleted when deleting a mu-site
*
* @param array $tables The tables to drop when deleting a mu-site.
* @param int $siteId The ID of the mu-site being deleted.
*
* @return array The tables to drop when deleting a mu-site, excluding the protected ones.
*/
public function protectGlobalTables($tables, $siteId)
{
$protectedTables = [\'terms\', \'term_taxonomy\'];
return array_filter($tables, function ($tableName) use ($protectedTables) {
return !in_array($tableName, $protectedTables);
}, ARRAY_FILTER_USE_KEY);
}
}