Select Page
使用 WP-CLI 管理 WordPress

使用 WP-CLI 管理 WordPress

WordPress 是全球最受歡迎的內容管理系統之一,提供了直觀的圖形使用者介面來管理網站。然而,對於開發者系統管理員來說,通過命令列介面管理 WordPress 也是非常必要的。這就是 WP-CLI 發揮作用的地方。WP-CLI 是一個為 WordPress 站點提供的命令列工具,允許用戶快速執行許多任務,如安裝和更新插件、配置多站點安裝、生成內容等,而無需使用 Web 瀏覽器。

WP-CLI 的優勢

  • 效率:通過命令列執行任務通常比使用圖形使用者介面更快。
  • 自動化:可以輕鬆地將命令腳本化和自動化,以便批量處理任務。
  • 無需 GUI:對於僅命令列介面訪問的伺服器,這是管理 WordPress 站點的理想選擇。

安裝 WP-CLI

WP-CLI 的安裝過程簡單直接,可以通過幾個簡單的步驟在任何類 UNIX 系統上安裝(包括 MacOS、Linux 發行版和 Windows 的 WSL)。

下載 WP-CLI: 首先,使用 curlwget 命令下載 WP-CLI 的 Phar 檔案。

使用 curl:

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

或者使用 wget:

wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

驗證 Phar 檔案是否可執行: 執行以下命令測試 wp-cli.phar 是否正常工作:

php wp-cli.phar --info

將它變成執行檔: 將下載的檔案轉換為可執行檔案,並移動到全域路徑中,以便從任何位置訪問 WP-CLI。

chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

驗證及測試WP-CLI: 輸入以下命令以確認 WP-CLI 正確安裝:

wp --info

會看到結果如下

以下示範一些簡單的功能

檢查 WordPress 核心檔案更新

wp core check-update

安裝插件

wp plugin install [plugin-name] --activate

更新單一外掛

wp plugin update [plugin-name]

更新所有插件

wp plugin update --all

創建新的用戶

wp user create bob [email protected] --role=author

WordPress 性能優化:使用 NGINX FastCGI Cache 提高頁面加載速度

在許多 WordPress 網站運營者的心中,提升網站載入速度始終是一項持續的任務。快速的載入速度不僅能改善用戶體驗,降低跳出率,還能在搜索引擎優化(SEO)上取得更好的成績。本文將引導您如何通過配置 NGINX 的 FastCGI Cache 來提升您的 WordPress 網站載入速度。

為什麼選擇 NGINX 的 FastCGI Cache?

NGINX 作為一款高效能的 Web 伺服器,其 FastCGI Cache 功能可以對動態內容(如 WordPress 生成的頁面)進行快取,從而減少對後端伺服器的請求,提高頁面載入速度。與其他快取方法相比,FastCGI Cache 直接在 Web 伺服器層面進行操作,能更精確地控制快取內容及其有效期。

步驟一:設定快取儲存路徑

建立快取存放的路徑,注意目錄擁有者是 www-data

sudo mkdir -p /etc/nginx/cache
sudo chown -R www-data:www-data /etc/nginx/cache

下面的設定是放在記憶體中的設定,如果你想要把快取放在記憶體內,要用下面這一個

sudo mkdir -p /var/run/cache/nginx
sudo chown -R www-data:www-data /var/run/cache/nginx

首先,您需要在 NGINX 配置文件中指定快取的儲存路徑及其他相關參數。打開您的 NGINX 配置文件(通常位於 /etc/nginx/nginx.conf),並添加以下配置:

http {
    ...
    fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=WORDPRESS_CACHE:100m inactive=60m max_size=256m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
    fastcgi_cache_use_stale error timeout invalid_header http_500;
    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
    ...
}

這段配置創建了一個名為 WORDPRESS_CACHE 的快取區域,並將其儲存路徑設定為 /etc/nginx/cachelevels=1:2 定義了目錄結構,keys_zone 指定了快取鍵的儲存空間大小,1 MB 的記憶體大約可以存放八千個左右的鍵值,也就是說若設定為 16 MB 的話(16m),大約可以快取 128,000 個左右的網址,max_size 是設定快取檔案的總容量上限(也就是放在 /etc/nginx/cache 中的檔案大小上限),inactive=60m 表示如果快取內容在60分鐘內未被訪問,則會被自動清除。

步驟二:啟用 FastCGI Cache

接下來,在處理 PHP 請求的 location 塊中啟用 FastCGI Cache。這通常在您站點的伺服器配置中(例如 /etc/nginx/sites-available/yourdomain.com):

server {
    ...
    set $skip_cache 0;

	# POST 請求不用快取
	if ($request_method = POST) {
    	set $skip_cache 1;
  	}

  	# 若有 query 參數的網址不用快取
  	if ($query_string != "") {
      	set $skip_cache 1;
  	}

  	# 特殊的網址不用快取
  	if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
      	set $skip_cache 1;
  	}

  	# 已登入使用者、留言者不用快取
  	if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
      	set $skip_cache 1;
  	}
    
    #正在維護模式中也略過
	if (-f "$document_root/.maintenance") {
    	set $skip_cache 1;
	}

  	# 加入快取資訊表頭(除錯用)
  	add_header X-Cache $upstream_cache_status;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
    	include fastcgi.conf;
        
        # FastCGI 快取設定
        fastcgi_cache WORDPRESS_CACHE;
        fastcgi_cache_valid 200 301 302 1d;
        fastcgi_cache_bypass $skip_cache;
    	fastcgi_no_cache $skip_cache;
        
        # 可以加入除錯用的標頭
        add_header X-Cache "$upstream_cache_status From $host";
    	add_header Cache-Control  max-age=0;
    	add_header Nginx-Cache "$upstream_cache_status";
    	add_header Last-Modified $date_gmt;
    }
    ...
}

這裡,fastcgi_cache 指令啟用了快取,並指定使用前面創建的快取區域。fastcgi_cache_valid 200 60m 表示成功的響應(HTTP 200 狀態碼)將被快取60分鐘。

步驟三:細化快取規則

為了避免快取敏感內容或確保特定條件下的頁面不被快取,您可以進一步細化快取規則。例如,避免快取已登入用戶的內容:

fastcgi_cache_bypass $cookie_user_logged_in;
fastcgi_no_cache $cookie_user_logged_in;

這些指令確保當 user_logged_in cookie 存在時,快取將被繞過。

清除快取

利用指令清除所有的快取

rm -rf /path/to/your/nginx/cache/*

利用 API 清除快取

首先去取 nginx 的 config 檔案中加入以下設定

location /purge_cache/ {
    allow 127.0.0.1; # 允許本地
    allow '多個主機ip';
    deny all; # 拒绝其他所有请求
    fastcgi_cache_purge WORDPRESS_CACHE $scheme$request_method$host$request_uri;
}

接下來就可以安裝 Nginx Helper 或是透過呼叫API網址清除快取

curl -X GET http://your-domain.com/purge_cache/the_uri_to_purge

區分手機版本和電腦版本

map $http_user_agent $is_desktop {
    default 0;
    ~*linux.*android|windows\s+(?:ce|phone) 0; # exceptions to the rule
    ~*spider|crawl|slurp|bot 1; # bots
    ~*windows|linux|os\s+x\s*[\d\._]+|solaris|bsd 1; # OSes
}

## Revert the logic.
map $is_desktop $is_mobile {
    1 0;
    0 1;
}
add_header x-ua-device $is_mobile;

# cache key 要加入 is_moubile
fastcgi_cache_key "$scheme$request_method$host$request_uri$is_mobile";

將快取放在記憶體,開機要自動執行

若是你把快取得存放路徑設定在記憶體中 /var/run ,那要記得設定重開機自動要建立該目錄,並且讓nginx重生效才行

先建立一個執行檔,執行重開機的設定

nano start-fastcgi.sh
chmod +x start-fastcgi.sh

start-fastcgi.sh的內容如下

mkdir -p /var/run/cache/nginx
chown -R www-data:www-data /var/run/cache/nginx
systemctl restart nginx

建立開機自動執行檔

sudo nano /etc/rc.local

rc.local 內容如下

#!/bin/bash
bash /home/yourname/start-fastcgi.sh

exit 0

設定開機自動執行

如果之前完全沒有設定過開機自動執行,那你會需要先設定開機自動執行的環境

rc-local 創建一個 Systemd 單元文件

sudo nano /etc/systemd/system/rc-local.service

將以下內容添加到文件中:

[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target

啟用並啟動服務

現在您有了一個為 rc-local 正確配置的 systemd 服務文件,您可以啟用並啟動它:

sudo chmod +x /etc/rc.local
sudo systemctl enable rc-local.service
sudo systemctl start rc-local.service

常見問題

無法使用 purage_all 功能,可以重新編譯 Nginx ,加入參數 –add-module=/path/to/src/ngx_cache_purge-2.3.1

Nginx Helper 的替代 Nginx FastCGI Cache

如何在WordPress中使用Object Cache Pro提升網站效能

如何在WordPress中使用Object Cache Pro提升網站效能

在處理大量數據和高流量的情況下,WordPress網站可能會面臨效能問題。這時,使用高效的緩存解決方案變得尤為重要。Object Cache Pro是一款專業級的物件緩存插件,它能夠顯著提升WordPress網站的性能和響應速度。本文將介紹如何在WordPress中安裝和配置Object Cache Pro。

安裝Object Cache Pro

步驟1:獲取插件

先從Object Cache Pro官方網站購買插件。完成後會取得授權金鑰。

步驟2:上傳並安裝插件

  1. 登入您的WordPress後台。
  2. 點擊「插件」>「新增」。
  3. 選擇「上傳插件」,然後選擇您下載的Object Cache Pro插件文件。
  4. 上傳並安裝插件。

步驟3:配置環境***

跟一般外掛不一樣的地方,這邊要自己手動在 /wp-content/wp-config.php 中,去配置參數,配置方法如下

define('WP_REDIS_CONFIG', [
    'token' => '<your-license-token>',
    'host' => '127.0.0.1',
    'port' => 6379,
    'database' => 0, // change for each site
    'maxttl' => 86400 * 7,
    'timeout' => 1.0,
    'read_timeout' => 1.0,
    'split_alloptions' => true,
    'debug' => false,
]);

define('WP_REDIS_DISABLED', false);

步驟4:清除舊資料

redis-cli flushall

步驟4:啟用插件

安裝完成後,點擊「啟用插件」。

進階配置Object Cache Pro

超快速度的配置

Object Cache Pro 進階配置,將序列話變成二進制,並且啟用快速壓縮等功能,再加入多主機支援

define('WP_REDIS_CONFIG', [
    'token' => '...',
    'host' => '127.0.0.1',
    'port' => 6379,
    'database' => 0, // change for each site
    'timeout' => 0.5,
    'read_timeout' => 0.5,
    'retry_interval' => 10,
    'retries' => 3,
    'backoff' => 'smart',
    'compression' => 'zstd', // `zstd` compresses smaller, `lz4` compresses faster
    'serializer' => 'igbinary',
    'async_flush' => true,
    'split_alloptions' => true,
    'prefetch' => true,
    'strict' => true,
    'debug' => false,
    'save_commands' => false,
    'prefix' => 'mysitename',
]);

define('WP_REDIS_DISABLED', getenv('WP_REDIS_DISABLED') ?: false);

安裝 PHP 外掛支援超快速配置

想要享用超快速的 object cache pro 配置的話,有兩個前提要先做好

1.安裝igbinary serializer

簡易安裝

pecl install igbinary
pecl install --configureoptions='enable-redis-igbinary="yes"' redis

原始檔安裝

https://github.com/igbinary/igbinary#installing

2.安裝 lzf/lz4/zstd compression

簡易安裝

# Use prompts
pecl install redis

# Skip prompts
pecl install --configureoptions='enable-redis-lzf="yes" enable-redis-zstd="yes" enable-redis-lz4="yes"' redis

原始檔安裝

https://github.com/phpredis/phpredis/blob/develop/INSTALL.md

測試和優化

安裝並配置好Object Cache Pro後,您應該進行測試,以確保一切運作正常。您可以使用速度測試工具如GTmetrix來檢查網站效能的提升。

結論

使用Object Cache Pro可以顯著提升WordPress網站的效能。通過合理配置和優化,您可以為您的用戶提供更快、更流暢的瀏覽體驗。

woocommerce 要移除商品頁面的相關商品

woocommerce 要移除商品頁面的相關商品

在預設的情況下,wordpress 中的 woocommerce 的商品頁面,會出現相關商品,如果需要移除,不需要安裝外掛,只要在佈景主題中的 function.php 加入一行程式碼即可

例如以下畫面,打算移除相關商品的區塊

我們找到使用中的佈景主題下的 function.php 並且加入以下程式碼即可

// 移除相關商品
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
在 wordpress 和 cloudflare 中啟用 HTTP/2 Server push,讓你網站速度飛奔

在 wordpress 和 cloudflare 中啟用 HTTP/2 Server push,讓你網站速度飛奔

什麼是 HTTP/2 Server Push?

HTTP/2 Server Push 是一項新的優化技術,允許伺服器在客戶端請求之前推送資源。這可以提高頁面載入速度而不需要等待瀏覽器先發出請求,因為它可以減少客戶端請求的數量,這意味著網頁所需的 CSS、JavaScript 或圖像文件可以更快地被載入,從而減少頁面加載時間。

在 Cloudflare 中啟用 HTTP/2 Server Push

要啟用 HTTP/2 Server Push,您需要登入到您的 Cloudflare 帳戶並轉到「Speed」頁籤。然後,您需要點擊「HTTP/2」頁籤並啟用「Server Push」。

啟用 HTTP/2 Server Push 的優勢

  • 提高頁面載入速度
  • 減少伺服器負載
  • 提高使用者體驗

WordPress 安裝 Cloudflare 外掛

在 wordpress 中,需要去安裝 cloudflare 官方的外掛

設定 wp-config.php

編輯 wp-config.php 檔案,並且加入設定

define('CLOUDFLARE_HTTP2_SERVER_PUSH_ACTIVE', true);