WordPress. Установка и использование WP-CLI

10.12.2019

Теги: CLICMSPHPWeb-разработкаWordPressНастройкаУстановка

WP-CLI позволяет управлять сайтами на WordPress через интерфейс командной строки. Можно выполнять как стандартные функции, вроде установки темы или плагина, так и операции, не поддерживаемые стандартным интерфейсом. Главным преимуществом использования WP-CLI является время, сэкономленное при установке, настройке и управлении сайтом.

Установка WP-CLI

Сначала скачаем WP-CLI с помощью утилиты curl:

$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

Удостверимся, что WP-CLI работает:

$ php wp-cli.phar --info
OS:    Linux 5.0.0-37-generic #40~18.04.1-Ubuntu SMP Thu Nov 14 12:06:39 UTC 2019 x86_64
Shell: /bin/bash
PHP binary: /usr/bin/php7.2
PHP version: 7.2.24-0ubuntu0.18.04.1
php.ini used: /etc/php/7.2/cli/php.ini
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /home/evgeniy
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.4.0

Сделаем wp-cli.phar исполняемым файлом:

$ chmod +x wp-cli.phar 

Перемещаем WP-CLI в окончательное местоположение:

$ sudo mv wp-cli.phar /usr/local/bin/wp

Команды WP-CLI

Информация о версии WP-CLI:

$ wp --info
OS: Linux 5.0.0-37-generic #40~18.04.1-Ubuntu SMP Thu Nov 14 12:06:39 UTC 2019 x86_64
Shell: /bin/bash
PHP binary: /usr/bin/php7.2
PHP version: 7.2.24-0ubuntu0.18.04.1
php.ini used: /etc/php/7.2/cli/php.ini
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /home/evgeniy
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.4.0

Список всех команд WP-CLI и документация:

$ wp --help
NAME
  wp
DESCRIPTION
  Manage WordPress through the command-line.
SYNOPSIS
  wp <command>
SUBCOMMANDS
  cache                 Adds, removes, fetches, and flushes the WP Object Cache object.
  cap                   Adds, removes, and lists capabilities of a user role.
  cli                   Reviews current WP-CLI info, checks for updates, or views defined aliases.
  comment               Creates, updates, deletes, and moderates comments.
  config                Generates and reads the wp-config.php file.
  core                  Downloads, installs, updates, and manages a WordPress installation.
  cron                  Tests, runs, and deletes WP-Cron events; manages WP-Cron schedules.
  db                    Performs basic database operations using credentials stored in wp-config.php.
  embed                 Inspects oEmbed providers, clears embed cache, and more.
  eval                  Executes arbitrary PHP code.
  eval-file             Loads and executes a PHP file.
  export                Exports WordPress content to a WXR file.
  help                  Gets help on WP-CLI, or on a specific command.
  i18n                  Provides internationalization tools for WordPress projects.
  import                Imports content from a given WXR file.
  language              Installs, activates, and manages language packs.
  maintenance-mode      Activates, deactivates or checks the status of the maintenance mode of a site.
  media                 Imports files as attachments, regenerates thumbnails, or lists registered image sizes.
  menu                  Lists, creates, assigns, and deletes the active theme's navigation menus.
  network               Perform network-wide operations.
  option                Retrieves and sets site options, including plugin and WordPress settings.
  package               Lists, installs, and removes WP-CLI packages.
  plugin                Manages plugins, including installs, activations, and updates.
  post                  Manages posts, content, and meta.
  post-type             Retrieves details on the site's registered post types.
  rewrite               Lists or flushes the site's rewrite rules, updates the permalink structure.
  role                  Manages user roles, including creating new roles and resetting to defaults.
  scaffold              Generates code for post types, taxonomies, plugins, child themes, etc.
  search-replace        Searches/replaces strings in the database.
  server                Launches PHP's built-in web server for a specific WordPress installation.
  shell                 Opens an interactive PHP console for running and testing PHP code.
  sidebar               Lists registered sidebars.
  site                  Creates, deletes, empties, moderates, and lists one or more sites on a multisite installation.
  super-admin           Lists, adds, or removes super admin users on a multisite installation.
  taxonomy              Retrieves information about registered taxonomies.
  term                  Manages taxonomy terms and term meta, with create, delete, and list commands.
  theme                 Manages themes, including installs, activations, and updates.
  transient             Adds, gets, and deletes entries in the WordPress Transient Cache.
  user                  Manages users, along with their roles, capabilities, and meta.
  widget                Manages widgets, including adding and moving them within sidebars.
....................

Можно просмотреть страницу помощи о каждой отдельной команде:

$ wp help comment
NAME
  wp comment
DESCRIPTION
  Creates, updates, deletes, and moderates comments.
SYNOPSIS
  wp comment <command>
SUBCOMMANDS
  approve        Approves a comment.
  count          Counts comments, on whole blog or on a given post.
  create         Creates a new comment.
  delete         Deletes a comment.
  exists         Verifies whether a comment exists.
  generate       Generates some number of new dummy comments.
  get            Gets the data of a single comment.
  list           Gets a list of comments.
  meta           Adds, updates, deletes, and lists comment custom fields.
  recount        Recalculates the comment_count value for one or more posts.
  spam           Marks a comment as spam.
  status         Gets the status of a comment.
  trash          Trashes a comment.
  unapprove      Unapproves a comment.
  unspam         Unmarks a comment as spam.
  untrash        Untrashes a comment.
  update         Updates one or more comments.
....................

У каждой команды есть свой список подкоманд. Можно пойти дальше и открыть страницу помощи для подкоманды этой команды:

$ wp help comment approve
NAME
  wp comment approve
DESCRIPTION
  Approves a comment.
SYNOPSIS
  wp comment approve <id>...
OPTIONS
  <id>...
    The IDs of the comments to approve.
EXAMPLES
    # Approve comment.
    $ wp comment approve 1337
    Success: Approved comment 1337.
....................

Установка WordPress

Теперь попробуем установить WordPress через командную строку. Для начала нужно создать базу данных и пользователя. Подключаемся к серверу MySQL:

  1. Создаем новую базу данных wp
  2. Создаем нового пользователя wp
  3. Выдаем пользователю wp все права на БД wp
$ mysql -uroot -pqwerty
> CREATE DATABASE wp;
> CREATE USER 'wp'@'localhost' IDENTIFIED BY 'qwerty';
> GRANT ALL PRIVILEGES ON wp.* TO 'wp'@'localhost';
> FLUSH PRIVILEGES;
> exit

Скачиваем файлы установщика WordPress:

$ cd /var/www/host1.loc
$ wp core download --locale=ru_RU
Downloading WordPress 4.7.3 (ru_RU)...
Success: WordPress downloaded.

Создаем файл wp-config.php с настройками подключения к БД:

$ wp core config --dbname=wp --dbuser=wp --dbpass=qwerty --dbhost=localhost --dbprefix=wp_
Success: Generated 'wp-config.php' file.

И, наконец, устанавливаем WordPress:

$ wp core install --url="host1.loc" --title="Сайт на WordPress" --admin_user="admin" \
> --admin_password="qwerty" --admin_email="admin@host1.loc"
Success: WordPress installed successfully.

Поиск: CLI • CMS • PHP • Web-разработка • WordPress • Установка • Настройка

Каталог оборудования
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Производители
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Функциональные группы
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.