wordpress-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WordPress Development Best Practices

WordPress开发最佳实践

Comprehensive development guidance for WordPress themes and plugins following 2025 standards.
遵循2025年标准的WordPress主题与插件综合开发指南。

What This Skill Provides

本Skill提供的内容

  1. Coding Standards - PHP, JS, CSS conventions following WordPress standards
  2. Custom Post Types - Complete CPT registration and management guide
  3. Security - Sanitization, escaping, nonces, capability checks
  4. Performance - Caching, query optimization, asset loading
  5. Hooks & Filters - Actions and filters reference with examples
  6. Template Hierarchy - Theme template structure and overrides
  1. 编码标准 - 遵循WordPress标准的PHP、JS、CSS规范
  2. 自定义文章类型 - 完整的CPT注册与管理指南
  3. 安全 - 数据清理、转义、nonce验证、权限检查
  4. 性能 - 缓存、查询优化、资源加载
  5. 钩子与过滤器 - 动作(Actions)和过滤器参考及示例
  6. 模板层级结构 - 主题模板结构与重写

Quick Reference

快速参考

Do's

应该做的

  • Use WordPress APIs (don't reinvent the wheel)
  • Sanitize all input (
    sanitize_*
    functions)
  • Escape all output (
    esc_*
    functions)
  • Use prepared statements for SQL (
    $wpdb->prepare
    )
  • Enqueue scripts/styles properly (
    wp_enqueue_*
    )
  • Use transients for expensive operations
  • Follow the template hierarchy
  • Use hooks instead of modifying core
  • Prefix all functions, classes, and global variables
  • Use WP-CLI for automation tasks
  • 使用WordPress API(不要重复造轮子)
  • 对所有输入进行数据清理(使用
    sanitize_*
    函数)
  • 对所有输出进行转义(使用
    esc_*
    函数)
  • 对SQL查询使用预处理语句(
    $wpdb->prepare
  • 正确注册脚本/样式(使用
    wp_enqueue_*
    函数)
  • 对耗时操作使用临时缓存(transients)
  • 遵循模板层级结构
  • 使用钩子而非修改核心代码
  • 为所有函数、类和全局变量添加前缀
  • 使用WP-CLI完成自动化任务

Don'ts

不应该做的

  • Modify WordPress core files (NEVER)
  • Use
    query_posts()
    - use
    WP_Query
    instead
  • Echo untrusted data without escaping
  • Store sensitive data in plain text options
  • Use
    extract()
    on untrusted data
  • Suppress errors with
    @
    operator
  • Use deprecated functions
  • Hard-code URLs or file paths
  • Skip nonce verification on forms
  • Use
    mysql_*
    functions - use
    $wpdb
  • 修改WordPress核心文件(绝对禁止)
  • 使用
    query_posts()
    - 改用
    WP_Query
  • 直接输出未经过转义的不可信数据
  • 以明文形式存储敏感数据到选项中
  • 对不可信数据使用
    extract()
    函数
  • 使用
    @
    运算符抑制错误
  • 使用已弃用的函数
  • 硬编码URL或文件路径
  • 跳过表单的nonce验证
  • 使用
    mysql_*
    函数 - 改用
    $wpdb

Documentation

文档

Detailed documentation available in
/docs/
:
FileContents
coding-standards.mdPHP, JS, CSS naming and formatting
custom-post-types.mdCPT registration, labels, capabilities
security.mdInput/output handling, nonces, SQL safety
performance.mdCaching, optimization, lazy loading
hooks-filters.mdCommon actions/filters with examples
template-hierarchy.mdTemplate files and overrides
详细文档位于
/docs/
目录下:
文件内容
coding-standards.mdPHP、JS、CSS的命名与格式规范
custom-post-types.mdCPT注册、标签、权限设置
security.md输入/输出处理、nonce、SQL安全
performance.md缓存、优化、懒加载
hooks-filters.md常见动作/过滤器及示例
template-hierarchy.md模板文件与重写规则

Code Templates

代码模板

Ready-to-use templates in
/templates/
:
TemplatePurpose
custom-post-type.php
CPT registration boilerplate
taxonomy.php
Custom taxonomy registration
meta-box.php
Admin meta box with save handling
rest-api-endpoint.php
Custom REST API endpoint
plugin-skeleton/
Complete plugin starter files
可直接使用的模板位于
/templates/
目录下:
模板用途
custom-post-type.php
CPT注册模板代码
taxonomy.php
自定义分类法注册
meta-box.php
带保存处理的后台元框
rest-api-endpoint.php
自定义REST API端点
plugin-skeleton/
完整的插件启动文件

Usage Examples

使用示例

Create a Custom Post Type

创建自定义文章类型

Ask Claude:
  • "Create a 'Property' custom post type for real estate"
  • "Add a custom post type for team members with a photo field"
  • "Register a 'Portfolio' CPT with custom taxonomies"
向Claude提问:
  • "为房地产行业创建一个'Property'自定义文章类型"
  • "添加一个带有照片字段的团队成员自定义文章类型"
  • "注册一个带有自定义分类法的'Portfolio' CPT"

Security Review

安全审查

Ask Claude:
  • "Review this form handler for security issues"
  • "Check if this plugin follows WordPress security best practices"
  • "Add proper sanitization and escaping to this code"
向Claude提问:
  • "审查这个表单处理程序的安全问题"
  • "检查这个插件是否遵循WordPress安全最佳实践"
  • "为这段代码添加适当的数据清理与转义"

Performance Optimization

性能优化

Ask Claude:
  • "Optimize this WP_Query for better performance"
  • "Add caching to this expensive database operation"
  • "Review asset loading for this theme"
向Claude提问:
  • "优化这个WP_Query以提升性能"
  • "为这个耗时的数据库操作添加缓存"
  • "审查这个主题的资源加载情况"

Code Generation

代码生成

Use the scaffold script to generate boilerplate:
bash
undefined
使用脚手架脚本生成模板代码:
bash
undefined

Generate a custom post type

生成自定义文章类型

python3 /root/.claude/skills/wordpress-dev/scripts/scaffold.py
--type cpt
--name "Property"
--slug "property"
--output /path/to/theme/inc/
python3 /root/.claude/skills/wordpress-dev/scripts/scaffold.py
--type cpt
--name "Property"
--slug "property"
--output /path/to/theme/inc/

Generate a custom taxonomy

生成自定义分类法

python3 /root/.claude/skills/wordpress-dev/scripts/scaffold.py
--type taxonomy
--name "Property Type"
--slug "property-type"
--post-type "property"
--output /path/to/theme/inc/
undefined
python3 /root/.claude/skills/wordpress-dev/scripts/scaffold.py
--type taxonomy
--name "Property Type"
--slug "property-type"
--post-type "property"
--output /path/to/theme/inc/
undefined

WordPress 6.x / Block Theme Notes

WordPress 6.x / 区块主题说明

Full Site Editing (FSE)

全站编辑(FSE)

For block themes (WordPress 6.0+):
theme/
├── theme.json          # Global styles and settings
├── templates/          # Block templates (HTML)
│   ├── index.html
│   ├── single.html
│   └── page.html
├── parts/              # Block template parts
│   ├── header.html
│   └── footer.html
└── patterns/           # Block patterns
    └── hero.php
对于区块主题(WordPress 6.0+):
theme/
├── theme.json          # 全局样式与设置
├── templates/          # 区块模板(HTML)
│   ├── index.html
│   ├── single.html
│   └── page.html
├── parts/              # 区块模板部件
│   ├── header.html
│   └── footer.html
└── patterns/           # 区块模式
    └── hero.php

theme.json Best Practices

theme.json最佳实践

json
{
  "$schema": "https://schemas.wp.org/trunk/theme.json",
  "version": 2,
  "settings": {
    "color": {
      "palette": [
        {"slug": "primary", "color": "#1a1a1a", "name": "Primary"}
      ]
    },
    "typography": {
      "fontFamilies": [
        {"fontFamily": "Inter, sans-serif", "slug": "body", "name": "Body"}
      ]
    },
    "spacing": {
      "units": ["px", "rem", "%"]
    }
  }
}
json
{
  "$schema": "https://schemas.wp.org/trunk/theme.json",
  "version": 2,
  "settings": {
    "color": {
      "palette": [
        {"slug": "primary", "color": "#1a1a1a", "name": "Primary"}
      ]
    },
    "typography": {
      "fontFamilies": [
        {"fontFamily": "Inter, sans-serif", "slug": "body", "name": "Body"}
      ]
    },
    "spacing": {
      "units": ["px", "rem", "%"]
    }
  }
}

Common Patterns

常见模式

Safe Database Query

安全数据库查询

php
global $wpdb;
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s",
        'property',
        'publish'
    )
);
php
global $wpdb;
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s",
        'property',
        'publish'
    )
);

AJAX Handler

AJAX处理程序

php
// Register AJAX action
add_action('wp_ajax_my_action', 'my_ajax_handler');
add_action('wp_ajax_nopriv_my_action', 'my_ajax_handler');

function my_ajax_handler() {
    // Verify nonce
    check_ajax_referer('my_nonce', 'security');

    // Check capability
    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Unauthorized', 403);
    }

    // Sanitize input
    $data = sanitize_text_field($_POST['data']);

    // Process and respond
    wp_send_json_success(['message' => 'Done']);
}
php
// 注册AJAX动作
add_action('wp_ajax_my_action', 'my_ajax_handler');
add_action('wp_ajax_nopriv_my_action', 'my_ajax_handler');

function my_ajax_handler() {
    // 验证nonce
    check_ajax_referer('my_nonce', 'security');

    // 检查权限
    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Unauthorized', 403);
    }

    // 清理输入数据
    $data = sanitize_text_field($_POST['data']);

    // 处理并返回响应
    wp_send_json_success(['message' => 'Done']);
}

Enqueue Scripts Properly

正确注册脚本

php
function theme_enqueue_assets() {
    // CSS
    wp_enqueue_style(
        'theme-style',
        get_stylesheet_uri(),
        [],
        filemtime(get_stylesheet_directory() . '/style.css')
    );

    // JS with dependencies
    wp_enqueue_script(
        'theme-main',
        get_theme_file_uri('/assets/js/main.js'),
        ['jquery'],
        filemtime(get_theme_file_path('/assets/js/main.js')),
        true // In footer
    );

    // Localize for AJAX
    wp_localize_script('theme-main', 'themeData', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('theme_nonce'),
    ]);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_assets');
php
function theme_enqueue_assets() {
    // CSS
    wp_enqueue_style(
        'theme-style',
        get_stylesheet_uri(),
        [],
        filemtime(get_stylesheet_directory() . '/style.css')
    );

    // 带依赖的JS
    wp_enqueue_script(
        'theme-main',
        get_theme_file_uri('/assets/js/main.js'),
        ['jquery'],
        filemtime(get_theme_file_path('/assets/js/main.js')),
        true // 在页脚加载
    );

    // 为AJAX本地化脚本
    wp_localize_script('theme-main', 'themeData', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('theme_nonce'),
    ]);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_assets');

Related Skills

相关Skills

  • wordpress-admin: Page/post management, WP-CLI, REST API
  • seo-optimizer: Yoast/Rank Math audit and optimization
  • visual-qa: Screenshot testing with animation handling
  • brand-guide: Brand documentation generation
  • wordpress-admin: 页面/文章管理、WP-CLI、REST API
  • seo-optimizer: Yoast/Rank Math审核与优化
  • visual-qa: 带动画处理的截图测试
  • brand-guide: 品牌文档生成

Resources

资源