dark-kitt/wordpress-theme-configuration

WordPress 主题配置 MU-插件,包括多个 WordPress 钩子以改进主题

安装: 5

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:wordpress-muplugin

1.0.0 2024-04-29 07:08 UTC

This package is auto-updated.

Last update: 2024-09-29 08:37:02 UTC


README

项目: 第 1 部分, 第 2 部分, 第 3 部分

简介

一个作为 MU-Plugin 编写的 WordPress 主题配置基础,包括多个 WordPress 钩子以改进您的主题。使用以下列出的方法在 functions.php 文件中配置所选主题。

需要 Autoloader MU-Plugin 以通过 WordPress 加载此插件。在执行 composer update 后,将 mu-plugin-autoloader.php 文件复制到 /mu-plugins 目录中,以自动加载 WordPress 主题配置 MU-插件。

注意:REST API 使用 JWT 认证用于 WP REST API 以确保 API 端点的安全性。

通用 WordPress 配置放在 base-configuration.php 文件中。对于每个类型/部分,您可以在 /traits 目录中找到一个 PHP Trait。例如:attachment.php 文件用于媒体库设置,post.php 文件用于帖子设置等。

注意:Gutenberg 编辑器始终禁用! 如果 WP_HOME 与 WP_SITEURL 不同,Gutenberg 编辑器会抛出多个错误。如果您对此感兴趣,请查看 Github WordPress / gutenberg (问题 1761)。

使用 ACF (高级自定义字段) 或安装 Classic Editor 插件,向每个帖子/页面添加内容。

方法

使用传递的 参数数组 控制每个方法或使用默认设置。如果您对默认设置感兴趣、想查看每个参数或设置自己的自定义默认设置,请查看 /trait 目录中的 trait 文件。

要求

内容维护(可选)

注意:如果您需要一种简单的方法来安装此项目及其所有要求,请查看 WordPress 模板 项目的 第 1 部分

安装

composer require dark-kitt/wordpress-theme-configuration

如果您有特定的 MU-插件目录路径,请将以下行添加到您的 composer.json 文件中。

"extra": {
  "installer-paths": {
    "path/to/mu-plugins/{$name}/": [
      "type:wordpress-muplugin"
    ]
  },
  "wordpress-install-dir": "path/to/wordpress"
},

之后,使用位于 /themes/your-theme 目录中的 functions.php 文件配置插件。如果您想使用 REST_API() 方法,别忘了插入 JWT Authentication for WP REST API

注意:对于您的 VCS 存储库的特定提交 "require": { "vendor/repo_name": "dev-main#eec8698" } (分支#提交)。

常见的 composer 命令

composer install
composer update
# package control
composer require verdor/package
composer remove verdor/package

composer clear-cache
composer show -i # installed packages

WordPress MU-插件自动加载器

wordpress-mu-plugin-autoloader 是一个基于 richardtape/subdir-loader.php Github Gist 的 WordPress MU 插件。将 mu-plugin-autoloader.php 文件复制到 /mu-plugins 目录中,以自动加载 MU 插件。

方法 [ 参数 ]

通用 WordPress 配置放置在 base-configuration.php 文件中。对于每个 WordPress 的类型/部分,您可以在 /traits 目录中找到一个 PHP Trait。查看 example.function.php 文件以获取有关用法以及如何在您的 /themes/your-theme 目录中的 functions.php 文件中配置主题的知识。

get_instance()

执行单例实例并返回自身。

$kitt_instance = KiTT\ThemeSetUp::get_instance();

set_up_theme( $wpdb, $wp_rewrite, $pagenow, array $args = defaults )

设置定义的全局变量 $wpdb$wp_rewrite$pagenow 并调用主主题设置方法。此方法还将调用 meta_box();company_settings(); 方法,包括自定义的 SEO 元数据框、自定义的 首页 元数据框、自定义的 错误页面 元数据框和 公司 菜单页面。set_up_theme() 方法允许您为 WordPress 安装语言并设置 ACF (高级自定义字段) 的进一步设置。所有默认参数如下。

global $wpdb,
  $wp_rewrite,
  $pagenow;

$kitt_instance = KiTT\ThemeSetUp::get_instance();
$kitt_instance->set_up_theme(
  $wpdb, /** reqiured */
  $wp_rewrite, /** reqiured */
  $pagenow, /** reqiured */
  [
    'set_up' => [
      /** custom favicon, logos and login logo url */
      'favicon' => $kitt_instance->theme_url . '/img/wp-favicon.png',
      'login_logo' => $kitt_instance->theme_url . '/img/wp-login-logo.svg',
      'login_logo_url' => WP_HOME,
      'admin_bar_logo' => $kitt_instance->theme_url . '/img/wp-admin-bar-logo.svg',
      'permalink_structure' => '/%postname%/',
      'default_user_role' => 'editor',
      'remove_welcome' => true,
      /** 1 = Mon, 2 = Thu ... 7 = Sun */
      'start_of_week' => 1,
      'timezone_string' => 'Europe/Berlin',
      'time_format' => 'H:i',
      'date_format' => 'd/m/Y',
      /**
       * install backend languages
       *
       * list of available translations
       * https://translate.wordpress.org/
       *
       * to remove a translation
       * delete the language code and the
       * files in the /web/storage/lang directory
       */
      'install_languages' => ['de_DE'],
      /** configure ACF (Advanced Custom Fields) */
      'ACF' => [
        /** add background color button to WYSIWYG editor */
        'WYSIWYG_BG_color' => true,
        'save_load' => [
          /** default: null, if null = ACF default -> /themes/your-theme/acf-json */
          'JSON_save' => constant('WP_STORAGE_DIR') . '/acf/acf-json',
          /** default: null, if null = ACF default -> /themes/your-theme/acf-json */
          'JSON_load' => constant('WP_STORAGE_DIR') . '/acf/acf-json',
          /** default: null, if null = ACF default -> /themes/your-theme/acf-json */
          'AutoSync_JSON_save' => constant('WP_STORAGE_DIR') . '/acf/acf-json',
          /** default: null, if null = ACF default -> /themes/your-theme/acf-json */
          'AutoSync_JSON_load' => constant('WP_STORAGE_DIR') . '/acf/acf-json',
          /** default: null, if null = ACF default -> /themes/your-theme/acf-php */
          'AutoSync_PHP_save' => constant('WP_STORAGE_DIR') . '/acf/acf-php',
          /** default: null, if null = ACF default -> /themes/your-theme/acf-php */
          'AutoSync_PHP_load' => constant('WP_STORAGE_DIR') . '/acf/acf-php'
        ],
        'google_api_key' => false
      ],
      /** add or remove company settings menu page */
      'company_settings' => true
    ]
  ]
);

post( array $args = defaults )

使用此方法修改 默认帖子部分。所有默认参数如下。

注意:使用 ACF (高级自定义字段) 或安装 经典编辑器插件,为每个帖子添加内容。

$kitt_instance->post([
  /** removes completely the default post section */
  'remove_post' => false,
  'post' => [
    /**
     * info:
     * https://developer.wordpress.org/reference/functions/remove_post_type_support/
     *
     * NOTE:
     * Gutenberg editor is always disabled
     */
    'remove_support' => ['excerpt', 'comments', 'trackbacks', 'author'],
    /** inspect the label attribute for="" in the screen options panel */
    'remove_meta_box' => ['commentsdiv', 'slugdiv'],
    /** en- or disable the SEO meta box */
    'SEO' => true,
    /** to disable tag support */
    'tag' => true,
    /** to disable category support */
    'category' => true,
    /** set default post slug */
    'post_slug' => false,
    /** rename default post section */
    'rename_labels' => [
      'name' => 'Posts',
      'singular_name' => 'Post',
      'menu_name' => 'Posts',
      'all_items' => 'All Posts',
      'add_new' => 'Add New',
      'add_new_item' => 'Add New Post',
      'edit' => 'Edit',
      'edit_item' => 'Edit Post',
      'new_item' => 'New Post',
      'view' => 'View',
      'view_item' => 'View Post',
      'search_items' => 'Search Posts',
      'not_found' => 'No Posts found',
      'not_found_in_trash' => 'No Posts found in trash'
    ]
  ]
]);

page( array $args = defaults )

使用此方法修改 默认页面部分。所有默认参数如下。

注意:使用 ACF (高级自定义字段) 或安装 经典编辑器插件,为每个页面添加内容。

$kitt_instance->page([
  /** removes completely the default page section */
  'remove_page' => false,
  'page' => [
    /**
     * info:
     * https://developer.wordpress.org/reference/functions/remove_post_type_support/
     *
     * NOTE:
     * Gutenberg editor is always disabled
     */
    'remove_support' => ['excerpt', 'comments', 'trackbacks', 'author'],
    /** inspect the label attribute for="" in the screen options panel */
    'remove_meta_box' => ['commentsdiv', 'slugdiv'],
    /** en- or disable the SEO meta box */
    'SEO' => true,
    /** to enable tag support */
    'tag' => true,
    /** to enable category support */
    'category' => true,
    /** rename default post section */
    'rename_labels' => [
      'name' => 'Pages',
      'singular_name' => 'Page',
      'menu_name' => 'Pages',
      'all_items' => 'All Pages',
      'add_new' => 'Add New',
      'add_new_item' => 'Add New Page',
      'edit' => 'Edit',
      'edit_item' => 'Edit Page',
      'new_item' => 'New Page',
      'view' => 'View',
      'view_item' => 'View Page',
      'search_items' => 'Search Pages',
      'not_found' => 'No Pages found',
      'not_found_in_trash' => 'No Pages found in trash'
    ]
  ]
]);

attachment( array $args = defaults )

设置 媒体库 的选项。所有默认参数如下。

注意:如果之前激活了另一个主题并且 新上传目录 不同,请检查项目中的旧上传目录,并在不再需要时手动删除它。

注意:此方法还可以添加 "查找重复" 附件模态框,该模态框遍历数据库并比较图像以查找重复项。

$kitt_instance->attachment([
  'attachment' => [
    /** to enable tag support */
    'tag' => false,
    /** to enable category support */
    'category' => false,
    /** enable search duplicates support */
    'search_duplicates' => true
  ],
  /**
   * set custom upload mimes
   *
   * extend_defaults = true|false
   * true = merges the default upload mimes
   * false = replaces the default upload mimes
   *
   * list of defaulst:
   * https://developer.wordpress.org/reference/functions/get_allowed_mime_types/
   */
  'upload_mimes' => [
    'extend_defaults' => true,
    'jpg|jpeg|jpe' => 'image/jpeg',
    'gif' => 'image/gif',
    'png' => 'image/png',
    /**
     * NOTE:
     * the XML declaration is required
     * in each SVG file, otherwise
     * the SVG upload is not accepted
     *
     * enter the version and the encoding
     * charset at the top of each SVG file
     *
     * <?xml version="1.0" encoding="utf-8"?>
     * <svg xmlns="http://www.w3.org/2000/svg" ... viewBox="0 0 100 57">
     *     ...
     * </svg>
     */
    'svg' => 'image/svg+xml',
    'pdf' => 'application/pdf',
    'mp3|m4a|m4b' => 'audio/mpeg',
    'mp4|m4v' => 'video/mp4',
    'zip' => 'application/zip'
  ],
  'options_media' => [
    /** WP default 150x150px */
    'thumbnail_size' => [
        'thumbnail_size_w' => 150,
        'thumbnail_size_h' => 150
    ],
    /** WP default 1 */
    'thumbnail_crop' => 1,
    /** WP default 300x300px */
    'medium_size' => [
        'medium_size_w' => 300,
        'medium_size_h' => 300
    ],
    /** WP default 768x768px */
    'medium_large_size' => [
        'medium_large_size_w' => 768,
        'medium_large_size_h' => 768
    ],
    /** WP default 1024x1024px */
    'large_size' => [
        'large_size_w' => 1024,
        'large_size_h' => 1024
    ],
    /** WP default 0 */
    'uploads_yearmonth' => 1,
    /** WP default open */
    'ping_status' => 'closed',
    /** WP default open */
    'comment_status' => 'closed',
    /** /wp-content/uploads */
    'upload_path' => constant('WP_UPLOAD_DIR'),
    /** http://127.0.0.1/uploads */
    'upload_url_path' => constant('WP_UPLOAD_URL')
  ]
]);

comments( array $args = defaults )

从 WordPress 完全移除 评论

$kitt_instance->comments([
  /** removes completely the default comments section */
  'remove_comments' => true
]);

menu( array $args = defaults )

此方法将 替换外观 子菜单页面到页面部分下方的 顶级 页面上的菜单(nav-menus.php)部分。此外,此方法还为 编辑器 角色添加了对菜单部分的 支持(=> 编辑器可以编辑菜单)。

$kitt_instance->menu([
  /** register main menu locations */
  'menu' => [
    'locations'  => [
      'header' => 'Header',
      'main' => 'Main',
      'footer' => 'Footer'
    ]
  ]
]);

custom_post_type( array $args = defaults )

这是一个包含一些额外选项的 register_post_type 方法。必须指定 slug 以注册自定义 菜单位置 并使用自定义 首页元数据框。所有默认参数如下。

/**
 * register new post type
 * example: "Pages EN"
 *
 * menu icon info:
 * https://developer.wordpress.org/resource/dashicons/#menu
 */
$kitt_instance->custom_post_type([
  'custom_post_type' => [
    /** similar to the WP method */
    'post_type' => 'pages_en',
    'description' => 'Pages EN',
    'capability_type' => 'post',
    'public' => true,
    'show_ui'  => true,
    'show_in_menu' => true,
    'map_meta_cap' => true,
    'hierarchical' => true,
    'query_var' => true,
    'has_archive' => true,
    'rewrite' => ['slug' => 'en'],
    'supports' => ['title', 'revisions', 'page-attributes', 'thumbnail', 'custom-fields', 'post-formats'],
    'menu_position' => 21,
    'menu_icon' => 'dashicons-admin-page',
    'taxonomies' => ['post_tag', 'category'],
    'labels' => [
      'name' => 'Pages EN',
      'singular_name' => 'Page EN',
      'menu_name' => 'Pages EN',
      'all_items' => 'All EN Pages',
      'add_new' => 'Add New',
      'add_new_item' => 'Add New EN Page',
      'edit' => 'Edit',
      'edit_item' => 'Edit EN Page',
      'new_item' => 'New EN Page',
      'view' => 'View',
      'view_item' => 'View EN Page',
      'search_items' => 'Search EN Pages',
      'not_found' => 'No EN Pages found',
      'not_found_in_trash' => 'No EN Pages found in trash',
      'attributes' => 'Page Attributes'
    ],
    'tag' => true,
    'category' => true,
    'remove_meta_box' => ['commentsdiv', 'slugdiv'],
    /**
     * dashboard at a glance widget icon
     * post-count, page-count, comment-count
     * or custom CSS class
     */
    'dashboard_icon' => 'page-count',
    /**
     * menu locations will be registered if a slug exists
     * caution, do not overwrite existing locations
     */
    'menu_locations' => [
      'header_en' => 'Header EN',
      'main_en' => 'Main EN',
      'footer_en' => 'Footer EN'
    ],
    /** add or remove SEO support */
    'SEO' => true
  ]
]);

REST_API( array $args = defaults )

REST_API() 方法使用 JWT 认证用于 WP REST API 来保护 API 端点。它还使用 PHP Mailer 通过 REST 路由发送电子邮件。在下面的示例中,您可以看到如何可选地使用此实例来配置 PHP Mailer 以用于您的表单。您还可以通过 POST 请求正文发送服务器 设置,使用 axiosjQuery 或其他发送请求的方式。

在您配置自定义 REST-API 时,需要创建一个拥有 rest_api_user 角色的用户。这很重要,因为具有 rest_api_user 角色的用户只能访问 REST-API,而不能访问后端系统。

如果您使用 Postman 进行 API 请求测试,要获取 WP REST API 的 JWT 认证的 token,请将 usernamepassword 作为 post body (raw/json) 数据发送。关于 \WP_REST_Server::CREATABLE 或其他方法的描述,请参阅 developer.wordpress.org。请深入查看 rest-api.php 文件,以获取更多关于处理的信息。

使用现有实例将额外的路由方法($kitt_instance->rest_routes['posts'][] = [])推送到现有路由,或将全新路由($kitt_instance->rest_routes['new_route'][] = [])注册到您的 REST API 配置中。

注意:axios GET (可读)请求不能通过 body 发送数据。

示例:定义您的自定义 REST-API

$kitt_instance->REST_API([
  'rest_api' => [
    /**
     * set the namespace for your routes
     * => example.com/wp-json/->namespace<-/route
     */
    'namespace' => explode('.', parse_url(WP_HOME)['host'])[0],
    /** removes the default REST API */
    'remove_default' => true,
    /**
     * examples:
     * 'Access-Control-Allow-Origin: ' . WP_HOME
     * 'Access-Control-Allow-Methods: POST, GET'
     * 'Access-Control-Allow-Credentials: true'
     * 'Access-Control-Max-Age: 600'
     */
    'headers' => [
      'Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type',
      'Access-Control-Allow-Origin: ' . WP_HOME,
      'Access-Control-Allow-Methods: POST, GET',
      'Access-Control-Allow-Credentials: true',
      'Access-Control-Max-Age: 600'
    ],
    /** JWT token arguments */
    'token' => [
      'expiration_time' => time() + (DAY_IN_SECONDS * 7),
      'header' => 'Access-Control-Allow-Headers, Access-Control-Allow-Origin, Content-Type, Authorization'
    ]
  ]
]);

示例:在 functions.php 文件中配置 PHP Mailer

/**
 * update email route arguments
 * set server settings
 *
 * update values with WP constants
 * or set your custom settings
 */
$kitt_instance->rest_routes['email']['args']['host'] = ['default' => constant('SMTP_HOST')]; // 'smtp.gmail.com'
$kitt_instance->rest_routes['email']['args']['SMTP_auth'] = ['default' => constant('SMTP_AUTH')]; // boolean
$kitt_instance->rest_routes['email']['args']['username'] = ['default' => constant('SMTP_USERNAME')]; // 'your@username.com'
/**
 * use google app password:
 * https://support.google.com/accounts/answer/185833?hl=en
 */
$kitt_instance->rest_routes['email']['args']['password'] = ['default' => constant('SMTP_PASSWORD')]; // 'app-password'
$kitt_instance->rest_routes['email']['args']['SMTP_secure'] = ['default' => constant('SMTP_SECURE')]; // 'tls'
$kitt_instance->rest_routes['email']['args']['port'] = ['default' => constant('SMTP_PORT')]; // 587
/** PHPMailer debug */
$kitt_instance->rest_routes['email']['args']['debug'] = ['default' => false];
/**
 * email test data
 *
 * test e.g. via postman
 * send data with route -> /wp-json/namespace/email
 */
$kitt_instance->rest_routes['email']['args']['set_from'] = ['default' => [
  'address' => 'from@address.com',
  'name' => 'User Joe'
]];
$kitt_instance->rest_routes['email']['args']['add_address'] = ['default' => [[
  'address' => 'add_to@address.com',
  'name' => 'User Foo'
]]];
$kitt_instance->rest_routes['email']['args']['add_reply_to'] = ['default' => [
  'address' => 'add_to_reply@address.com',
  'name' => 'User Bar'
]];

示例:在 functions.php 文件中添加自定义 REST 路由

/**
 * register custom REST routes
 *
 * functions.php
 * modifing default args
 * $kitt_instance->rest_routes['route']['args']['param'] = ['default' => 'value']
 *
 * add route
 * extend $this->rest_routes array
 * e.g.
 * $kitt_instance->rest_routes['endpoint'][] = [
 *     'methods'  => \WP_REST_Server::CREATABLE,
 *     'callback' => 'call_callback_API',
 *     'permission_callback' => 'edit_others_posts',
 *     'args' => [
 *        'param_one' => ['default' => 'one']
 *     ]
 * ];
 * add REST route method
 * extend $instance
 * e.g.
 * $kitt_instance->call_callback_API = function (\WP_REST_Request $request)
 * {
 *     // $_GET and $_POST params
 *     $params = $request->get_params();
 *     $response = new \WP_REST_Response($params, 200);
 *     return $response;
 * };
 */
$kitt_instance->rest_routes['endpoint'][] = [
  /**
   * add a custom REST route
   * example: return Vue.js routes
   *
   * const READABLE = 'GET';
   * const CREATABLE = 'POST';
   * ...
   * const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE';
   *
   * NOTE: axios GET request can not send data via body
   *
   * documentation
   * https://developer.wordpress.org/reference/classes/wp_rest_server/
   */
  'methods'  => \WP_REST_Server::CREATABLE,
  'callback' => 'my_custom_callback', // string required!!!
  /**
   * string required
   * ... current_user_can($route['permission_callback']); ...
   *
   * list of roles and capabilities
   * https://wordpresstheme.cn/support/article/roles-and-capabilities/
   */
  'permission_callback' => 'rest_api_user',
  /** set the defaults */
  'args' => [
    'param_one' => ['default' => false]
  ]
];

/**
 * add a custom REST callback method
 */
$kitt_instance->my_custom_callback = function (\WP_REST_Request $request) use ($kitt_instance)
{
  /** $_GET and $_POST params */
  $params = $request->get_params();
  /** get the default params */
  $default = $request->get_default_params();

  /** update posts default arguments with request data */
  $args = $kitt_instance->replace_val_in_array($default, $params);

  /** do stuff!!! */
  $response = "my custom response";

  return new \WP_REST_Response($response, 200);
};

注意:Gutenberg 编辑器始终处于禁用状态! 如果 WP_HOME 与 WP_SITEURL 不同,Gutenberg 编辑器会抛出多个错误。如果您感兴趣,请查看 Github WordPress / gutenberg (问题 1761)

使用 ACF (高级自定义字段) 或安装 Classic Editor 插件,向每个帖子/页面添加内容。

许可协议

包含内容