WordPress主题二次开发权威指南
WordPress主题二次开发权威指南
关于wordpress主题的下载可以在主题猫wordpress里搜索。
第一章 开发基础规范
1.1 子主题强制标准
/*
Theme Name: Custom Child
Template: parent-theme
Version: 1.0
Text Domain: child-theme
*/
add_action('wp_enqueue_scripts',function(){
wp_enqueue_style('parent-style',
get_template_directory_uri().'/style.css');
});
1.2 安全隔离机制
// 禁止直接访问
defined('ABSPATH') || exit;
// 生产环境配置
if(!WP_DEBUG){
error_reporting(0);
ini_set('display_errors','Off');
}
第二章 核心开发技术
2.1 动态模板加载
add_filter('template_include',function($template){
if(is_product() && current_user_can('wholesaler')){
return locate_template('wholesale-product.php');
}
return $template;
});
2.2 自定义文章循环
function get_custom_posts($post_type='product'){
$cache_key = md5('custom_posts_'.$post_type);
if(false === ($data = wp_cache_get($cache_key))){
$data = new WP_Query([
'post_type' => $post_type,
'posts_per_page' => 8,
'meta_key' => 'featured',
'meta_value' => 'yes'
]);
wp_cache_set($cache_key,$data,'posts',3600);
}
return $data;
}
第三章 高级功能实现
3.1 REST API扩展
add_action('rest_api_init',function(){
register_rest_route('custom/v1','/analytics',[
'methods' => 'GET',
'callback' => 'get_site_analytics',
'permission_callback' => '__return_true'
]);
});
3.2 实时通信系统
// 前端WebSocket实现
document.addEventListener('DOMContentLoaded',function(){
const ws = new WebSocket(`wss://${location.host}/ws`);
ws.onmessage = function(e){
const data = JSON.parse(e.data);
if(data.type === 'notification'){
showToast(data.content);
}
};
});
第四章 性能优化方案
4.1 智能资源加载
add_action('wp_enqueue_scripts',function(){
if(is_page('contact')){
wp_enqueue_script('contact-form',
get_theme_file_uri('/js/contact.min.js'),
[],'1.0',true);
}
});
4.2 数据库优化
-- 添加常用查询索引
ALTER TABLE wp_postmeta
ADD INDEX meta_key_index (meta_key(32));
第五章 安全防护体系
5.1 多层防御机制
// 输入过滤链
function process_input($input){
$input = sanitize_text_field($input);
$input = wp_kses_post($input);
return htmlspecialchars($input,ENT_QUOTES);
}
5.2 文件上传防护
add_filter('upload_mimes',function($mimes){
unset($mimes['exe'],$mimes['js'],$mimes['php']);
return $mimes;
});
附录A:开发禁忌清单
直接修改wp-config.php ❌
使用mysql_query() ❌
未验证的管理员操作 ❌
附录B:推荐调试工具
Query Monitor
Debug Bar
New Relic APM
浙公网安备 33010602011771号