close

(圖片來源)

WordPress & Laravel,這兩種PHP框架各有優缺點,WordPress 對於後台功能來說是非常完整與強大,但前台代碼較不易修改,而 Laravel 框架架構非常明瞭清晰,易於開發任何功能與頁面,若這兩者可以整合起來,那必定是一件非常美妙的事情。

 

整合測試一共有 6 個步驟:

1. 下載與安裝 wordpress 4.7.5

2. 安裝 Laravel 5.3

3. Laravel 引用 WordPress

4. 修改 Laravel View 測試 WordPress 串接

5. 優化串接方式

6. 測試 Laravel 撈取 WordPress DB 資料

 

Step1. 下載與安裝 wordpress 4.7.5

4.7.5 是我測試用的版本,若有興趣可以自行測試其他版本的整合,WordPress 繁體中文載點

 

下載下來後將 zip 檔移至 www 資料夾目錄下解壓縮,解壓縮完畢將資料夾重新命名成 wordpress_laravel (看個人想取什麼專案名稱),至 apache site-enabled 設定 conf (以 laragon 操作) 與設定 hosts:

 

conf:

<VirtualHost *:80>
    DocumentRoot "D:/laragon3/www/wordpress_laravel/" # 依自己路徑
    ServerName wp.site.com
    <Directory "D:/laragon3/www/wordpress_laravel/">   # 依自己路徑
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

 

hosts:

127.0.0.1 wp.site.com

 

打開瀏覽器並輸入 http://wp.site.com 後就開始 wordpress 一連串安裝行為,在此不贅述,安裝完畢後結果如下:

 

但我們其實不需要使用到 WordPress 的前台,所以到 wordpress_laravel 根目錄的 index.php 添加下方代碼(此段代碼必須加在檔首),如此一來若呼叫到 WordPress 前台都會被轉到後台:

/**
* 刪除WordPress前端
* 重定向到管理員登錄頁面
*/
header("Location: ./wp-admin");
exit();

 

Step2. 安裝 Laravel 5.3

利用 cmder 與 composer 指令來進行安裝,首先移到 www 目錄下,並在 cmder 執行下方指令:

composer create-project laravel/laravel=5.3 laravel53 --prefer-dist

 

安裝完畢後將 laravel53 資料夾移至 wordpress_laravel 目錄,目錄結構如下:

wp-admin/
wp-content/
wp-includes/
... other wordpress files ...
laravel53/ <-- laravel application
|-> app/
|-> bootstrap/
|-> config/
|-> public/
|-> ... other laravel files and directories ...

 

設定 apache site-enabled 的 conf 與設定 hosts:

 

conf:

<VirtualHost *:80>
    DocumentRoot "D:/laragon3/www/wordpress_laravel/laravel53/public/" # 依照自己目錄
    ServerName test.site.com
    <Directory "D:/laragon3/www/wordpress_laravel/laravel53/public/">  # 依照自己目錄
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

 

hosts:

127.0.0.1 test.site.com

 

打開瀏覽器並輸入 http://test.site.com 後就會看到下方畫面:

 

 

重要的提示!

不適用於 5.4 以上版本的 Laravel。WordPress 和 Laravel 都使用一個名為 __(用於翻譯目的)的函數,而WordPress 遺憾地沒有包含它們的函數 function_exists。這會導致 Cannot redeclare 錯誤,並且無法使用此解決方案。

 

衝突 function:

Laravel:\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php

if (! function_exists('__')) {
    /**
     * Translate the given message.
     *
     * @param  string  $key
     * @param  array  $replace
     * @param  string  $locale
     * @return \Illuminate\Contracts\Translation\Translator|string
     */
    function __($key = null, $replace = [], $locale = null)
    {
        return app('translator')->getFromJson($key, $replace, $locale);
    }
}

 

WordPress:\wp-includes\l10n.php

/**
* Retrieve the translation of $text.
*
* If there is no translation, or the text domain isn't loaded, the original text is returned.
*
* @since 2.1.0
*
* @param string $text   Text to translate.
* @param string $domain Optional. Text domain. Unique identifier for retrieving translated strings.
*                       Default 'default'.
* @return string Translated text.
*/
function __( $text, $domain = 'default' ) {
    return translate( $text, $domain );
}

 

Step3. Laravel 引用 WordPress

在 Laravel 框架中,我們可能需要得到 WordPress 的功能(接入內得到WordPress的內容get_header(),get_footer()等等)。為此,需在 bootstrap/app.php 檔案開始處添加下方代碼:

require '../../wp-load.php';

 

Step4. 修改 Laravel View 測試 WordPress 串接

現在我們可以在 Laravel 中使用 WordPress 的函數,將 /views/welcome.blade.php 改為下方代碼:

{!! get_header() !!}
<div class="container">
    <div class="content">
        <div class="title">Laravel 5</div>
    </div>
</div>
{!! get_footer() !!}

 

當我們刷新 http://test.site.com 後就會發現畫面改變了!這代表測試串接是成功的~效果如下:

 

Step5. 優化串接方式

Laravel 提供了 Service Provider 的服務與結構,在此可以利用 Service Provider 將 wordpress 包成一個 Service 進行載入,將步驟 3 的方式進行改寫,至 laravel53/app/Providers 目錄下新增 WordPressServiceProvider.php 檔案,並將下方代碼填入:

 

namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\File;
 
class WordPressServiceProvider extends ServiceProvider {
 
    protected $bootstrapFilePath = '../../wp-load.php';  // 載入 wp-load.php
 
    public function boot() {
        // Load assets (若有要利用 laravel css or js 來修改 wp 相關頁面,可以用此方式載入檔案)
        wp_enqueue_style('app', '/app/public/css/app.css'); // or whatever your css is called
        wp_enqueue_script('app', '/app/public/js/app.js');  // or whatever your js is called
    }
 
    public function register() {
        // Load wordpress bootstrap file
        if(File::exists($this->bootstrapFilePath)) {
            require_once $this->bootstrapFilePath;
        } else throw new \RuntimeException('WordPress Bootstrap file not found!');
    }
 
}

 

並將 WordPressServiceProvider 添加到 config/app.php:

/* ... */
'providers' => [
// ...
 
/*
* Application Service Providers...
*/
// ...
App\Providers\WordPressServiceProvider::class,

 

Step6. 測試 Laravel 撈取 WordPress DB 資料

由於剛安裝完的 laravel /routes/web.php 中只有下方代碼:

Route::get('/', function () {
    return view('welcome');
});

 

為了方便測試,我們在 /Http/Controllers/ 新增一個 HomeController.php ,代碼如下:

namespace App\Http\Controllers;
 
class HomeController extends Controller
{
 
    function index()
    {
        global $wpdb; // wordpress 取得 db 資料的全域變數
 
        $query = "SELECT * FROM wp_posts";
        $data['posts'] = $wpdb->get_results($query, OBJECT); // 取得多筆
 
        return view('welcome', compact('data'));
    }
}

 

並將 /routes/web.php 代碼修改如下:

Route::get('/', 'HomeController@index');
 
// Route::get('/', function () {
//     return view('welcome');
// });

 

將 WordPress 的文章資料取出並在 welcome.blade.php 顯示,所以我們也要將內容稍作調整:

{!! get_header() !!}
        <div class="container">
            <div class="content">
                <div class="title">下方是 wordpress 資料</div>
                <table>
                 <tr>
                     <th>id</th>
                     <th>post_author</th>
                     <th>post_date</th>
                     <th>post_title</th>
                     <th>post_content</th>
                 </tr>
                @foreach ($data['posts'] as $post)
                <tr>
                    <td>{{ $post->ID }}</td>
                    <td>{{ $post->post_author }}</td>
                    <td>{{ $post->post_date }}</td>
                    <td>{{ $post->post_title }}</td>
                    <td>{{ $post->post_content }}</td>
                </tr>
                @endforeach
                </table>
            </div>
        </div>
{!! get_footer() !!}

 

當我們再次刷新 http://test.site.com/ ,還真的可以取出並顯示 wordpress 文章~

這次的測試算是非常成功,如果可以更熟悉 WordPress 與 Laravel 的整合,我相信在網站開發上會有非常大的幫助!

 

參考:

Integrating Laravel into WordPress

Working with Laravel 4 or 5 and WordPress together

 

 

arrow
arrow
    文章標籤
    laravel wordpress php
    全站熱搜

    Mayuge 發表在 痞客邦 留言(3) 人氣()