😍Tạo một WordPress theme theo chuẩn OOP + Namespace

Chú ý: Người ta sử dụng use (1) khi đã có require_once, hoặc include trước đó và trong fiel đó sử dụng namespace MyTheme\Core (2)

use MyTheme\Core\Loader;

Cách 1: Sử dụng theo cách thông thường require_once

wp-content\themes\my-theme\functions.php (1)

<?php
if ( ! defined( 'ABSPATH' ) ) {
  exit;
}
require_once get_template_directory() . '/inc/Core/Loader.php';
use MyTheme\Core\Loader;
Loader::init();

wp-content\themes\my-theme\inc\Core\Loader.php (2)

<?php
namespace MyTheme\Core;
if ( ! defined( 'ABSPATH' ) ) {
  exit;
}
class Loader {
  public static function init() {
    require_once get_template_directory() . '/inc/Core/Theme.php';
    require_once get_template_directory() . '/inc/Setup/ThemeSetup.php';
    require_once get_template_directory() . '/inc/Setup/Enqueue.php';
    require_once get_template_directory() . '/inc/Hooks/Actions.php';
    require_once get_template_directory() . '/inc/Hooks/Filters.php';
    Theme::init();
  }
}

wp-content\themes\my-theme\inc\Core\Theme.php (3)

wp-content\themes\my-theme\inc\Setup\ThemeSetup.php (4)

wp-content\themes\my-theme\inc\Setup\Enqueue.php (5)

wp-content\themes\my-theme\inc\Hooks\Actions.php (6)

wp-content\themes\my-theme\inc\Hooks\Filters.php (7)

Việc sử dụng use ví dụ: use MyTheme\Hooks\Filters; trở lên linh động hơn rất nhiều

wp-content\themes\my-theme\inc\Core\Theme.php (8)

wp-content\themes\my-theme\inc\Setup\ThemeSetup.php (9)

Cách 2: Thậm chí còn dễ dàng hơn nhiều là dung autoload

wp-content\themes\my-theme\composer.json (10)

wp-content\themes\my-theme\functions.php (11)

wp-content\themes\my-theme\inc\Core\Loader.php (12)

wp-content\themes\my-theme\inc\Core\Theme.php (13)

Ta thấy nó ngắn gọn hơn nhiều nó không sử dụng require_once ví dụ: require_once get_template_directory() . '/inc/Setup/ThemeSetup.php'; (2) nữa mà khi sử dụng

Override Plugin Premium Addons for Elementor

wp-content\themes\my-theme\functions.php (14)

wp-content\themes\my-theme\inc\Overrides\PremiumAddons\Override.php (15)

wp-content\themes\my-theme\inc\Overrides\PremiumAddons\Widgets\Testimonial.php (16)

wp-content\themes\my-theme\inc\Core\Loader.php (17)

wp-content\themes\my-theme\inc\Core\Theme.php (18)

wp-content\themes\my-theme\index.php (19)

wp-content\themes\my-theme\templates\header.php (20)

wp-content\themes\my-theme\templates\footer.php (21)

Last updated