解决 WordPress 4.9 页面模板功能无法正常使用

WordPress 4.9.1 及以上版本已经默认修复该问题,建议直接更新到最新版本,无需再看本文下面的内容了!

WordPress 4.9 有一个重要更新是:在WP后台编辑主题和插件文件时,支持按层级显示所有文件。为了性能考虑,使用了 transient 缓存机制。但是却没有提供任何手动清除缓存的功能,导致有些用户升级到 WordPress 4.9 以后,发现“页面属性 – 模板”这个功能不能正常使用了,不显示主题自带的模板文件!

要解决这个问题,我们可以添加下面的代码到当前主题的 functions.php 就可以了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Plugin name: WP Trac #42573: Fix for theme template file caching.
 * Description: Flush the theme file cache each time the admin screens are loaded which uses the file list.
 * Plugin URI: https://core.trac.wordpress.org/ticket/42573
 * Author: Weston Ruter, XWP.
 * Author URI: https://weston.ruter.net
 */
function wp_42573_fix_template_caching( WP_Screen $current_screen ) {
	// Only flush the file cache with each request to post list table, edit post screen, or theme editor.
	if ( ! in_array( $current_screen->base, array( 'post', 'edit', 'theme-editor' ), true ) ) {
		return;
	}
	$theme = wp_get_theme();
	if ( ! $theme ) {
		return;
	}
	$cache_hash = md5( $theme->get_theme_root() . '/' . $theme->get_stylesheet() );
	$label = sanitize_key( 'files_' . $cache_hash . '-' . $theme->get( 'Version' ) );
	$transient_key = substr( $label, 0, 29 ) . md5( $label );
	delete_transient( $transient_key );
}
add_action( 'current_screen', 'wp_42573_fix_template_caching' );

/**
* Plugin name: WP Trac #42573: Fix for theme template file caching.
* Description: Flush the theme file cache each time the admin screens are loaded which uses the file list.
* Plugin URI: https://core.trac.wordpress.org/ticket/42573
* Author: Weston Ruter, XWP.
* Author URI: https://weston.ruter.net
*/
function wp_42573_fix_template_caching( WP_Screen $current_screen ) {
// Only flush the file cache with each request to post list table, edit post screen, or theme editor.
if ( ! in_array( $current_screen->base, array( ‘post’, ‘edit’, ‘theme-editor’ ), true ) ) {
return;
}
$theme = wp_get_theme();
if ( ! $theme ) {
return;
}
$cache_hash = md5( $theme->get_theme_root() . ‘/’ . $theme->get_stylesheet() );
$label = sanitize_key( ‘files_’ . $cache_hash . ‘-‘ . $theme->get( ‘Version’ ) );
$transient_key = substr( $label, 0, 29 ) . md5( $label );
delete_transient( $transient_key );
}
add_action( ‘current_screen’, ‘wp_42573_fix_template_caching’ );

如果你不想编辑代码,点击下载此插件安装启用即可:wp-42573

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号