我也面临同样的问题,并针对我们使用的旧主题get_option(\'theme_switched\')
. 此选项保存最后一个活动主题的值。
一个几乎完整的示例(仅缺少停用挂钩):
register_activation_hook( __FILE__, \'make_copy_wpse_7518\' );
add_action( \'switch_theme\', \'switching_theme_wpse_7518\', 10, 2 );
/**
* Theme switch
*/
function switching_theme_wpse_7518( $new_name, $new_theme )
{
# Remove template from old theme
$old_theme = get_option( \'theme_switched\' );
// I thought that get_theme_root would return the path to the old theme, but apparently not, hence the second $old_theme
$template_path = get_theme_root( $old_theme ) . "/$old_theme/plugin-template-file.php";
if( file_exists( $template_path ) )
unlink( $template_path );
# Copy template to newly activated theme
make_copy_wpse_7518();
}
/**
* Copy function, called on plugin activation and theme swap
*/
function make_copy_wpse_7518()
{
$source = dirname( __FILE__ ) . "/includes/plugin-template-file.php";
$destination = get_stylesheet_directory() . "/plugin-template-file.php";
copy_page_template_wpse_7518( $source, $destination );
}
/**
* Does the actual copy from plugin to template directory
* From https://github.com/tommcfarlin/page-template-example/
*/
function copy_page_template_wpse_7518( $source, $destination )
{
// Check if template already exists. If so don\'t copy it; otherwise, copy if
if( ! file_exists( $destination ) )
{
// Create an empty version of the file
touch( $destination );
// Read the source file starting from the beginning of the file
if( null != ( $handle = @fopen( $source, \'r\' ) ) )
{
// Read the contents of the file into a string.
// Read up to the length of the source file
if( null != ( $content = fread( $handle, filesize( $source ) ) ) )
{
// Relinquish the resource
fclose( $handle );
}
}
// Now open the file for reading and writing
if( null != ( $handle = @fopen( $destination, \'r+\' ) ) )
{
// Attempt to write the contents of the string
if( null != fwrite( $handle, $content, strlen( $content ) ) )
{
// Relinquish the resource
fclose( $handle );
}
}
}
}