预备任务在主题中创建一个目录,以包含布局拇指添加布局缩略图以反映模板的文件名。以下脚本使用tpl主页的格式。php。该图像将命名为homepage。jpg请注意,以下是概念证明。
方法1:仅JavaScript
Load the following only for post.php and post-new.php
add_action(\'admin_head-post.php\', \'template_thumbs\');
add_action(\'admin_head-post-new.php\', \'template_thumbs\');
function template_thumbs(){
global $post;
if($post->post_type != \'page\')
return;
$js = "
<script type=\'text/javascript\'>
jQuery(document).ready(function($){
//Define the page template select drop-down
var _template = $(\'#page-template\');
#Get the thumb on page load
if(_template.val())
get_template_thumb(_template.val());
//Sniff template changes
_template.change(function(){
//Get template file name
var _file = $(this).val();
if(_file)
get_template_thumb(_file);
});
});
function get_template_thumb(file){
//Define the path to your thumbs directory
var _thumb_path = \'/wp-content/themes/your-theme/img/layouts/\';
//Format thumb filename
file.replace(\'tpl-\', \'\');
file.replace(\'.php\', \'\');
file = _thumb_path + file + \'.jpg\';
//Remove previous thumbnail
$(\'.template-thumb\').remove();
//Insert thumbnail before the select box
$(this).before(\'<img class=\\\'template-thumb\\\' src=\\\' + file + \'\\\' alt=\\\'Layout\\\'>\');
}
</script>
";
echo $js;
}
方法2:AJAX+PHP如果这种方法不适用,我会启动一个XHR并检索缩略图。
add_action(\'admin_head-post.php\', \'template_thumbs_script\');
add_action(\'admin_head-post-new.php\', \'template_thumbs_script\');
function template_thumbs_script(){
global $post;
if($post->post_type != \'page\')
return;
$js = "
<script type=\'text/javascript\'>
jQuery(document).ready(function($){
//Sniff template changes
$(\'#page-template\').change(function(){
//Set $_POST data
var data = {
action: \'get_template_thumb\',
template: $(this).val()
};
//Send XHR
$.post(ajaxurl, data, function(response) {
if(response){
//remove previous thumb
$(\'.template-thumb\').remove();
//Insert thumb before select drop-down
$(\'#page-template\').before(response);
}
});
});
});
</script>
";
echo $js;
}
add_action(\'wp_ajax_get_template_thumb\', \'get_template_thumb\');
function get_template_thumb(){
#Verify Nonce
#Get template name
$template = esc_attr($_POST[\'template\']);
#Format image name
$img_file = str_replace(\'tpl-\', \'\', $template);
$img_file = str_replace(\'.php\', \'\', $template);
#Assuming this is in functions.php theme root. If not, make absolute path
$thumb_path = \'img/layouts/\';
#Check if file exists first
if(file_exists($thumb_path.$img_file.\'.jpg\'))
#Return an image tag
echo "<img class=\'template-thumb\' src=\'$img_file.jpg\' alt=\'Template Layout\'>";
exit;
}