作为服务提供商将 Wordpress 功能集成到 Laravel

Integrating Wordpress functions into Laravel as a Service Provider

我打算将 Laravel 用于我的 Wordpress 插件的 api。结构如下:

- main-directory
  - Laravel-dir
  - WordPress-dir

我已经为 Laravel 创建了一个 Wordpress 服务提供商,如下所示:

use File;
use Illuminate\Support\ServiceProvider;

class WordpressServiceProvider extends ServiceProvider
{

    protected $bootstrapFilePath = '../../wp/wp-load.php';

    public function boot()
    {
        wp_enqueue_style('app', '/app/public/app.css');
    }

    public function register()
    {
        if(File::exists($this->bootstrapFilePath)) {
            require_once $this->bootstrapFilePath;
        } else throw new \RuntimeException('Wordpress Bootstrap File Not Found');
    }
}

我还把它作为 provider => 添加到 Laravel-dir/config/app.php 下:

App\Providers\WordpressServiceProvider::class,

现在,当有人访问 Laravel 页面之一时,我需要检查 WordPress 管理员用户是否已登录。

跳至下面的'Edit':我已尝试is_admin()检查管理员用户。调用该函数有效(不抱怨),所以我假设我的服务提供商有效,但尽管我以 wp-admin 身份登录,is_admin() 函数始终 returns false


编辑: 我意识到 is_admin 是检查页面是否是管理页面。相反,我不得不使用 wp_get_current_user()

我尝试在我的 Wordpress 插件中使用 wp_get_current_user(),它 returns 所有管理员的信息。但是,如果我在 Laravel 中使用它,它会 returns 空数组集。

is_admin() 用于确定您是否在管理页面上,而不是您是否是管理员用户。

https://codex.wordpress.org/Function_Reference/is_admin

我自己 运行 遇到过类似的问题。这个问题是由我的系统结构引起的。

我 laravel 运行ning 在子域上,而 wordpress 运行ning 在根域上。在这种情况下,您无权访问子域中的根域 cookie。为了解决这个问题,我将我的 laravel 安装移动到我的 webroot 的子目录(其中安装了 wordpress),并为 nginx 创建了一个重写规则,以便从 www.yourdomain 为我的 laravel 安装提供服务。com/laravel.

您需要编辑 /etc/nginx/sites-available/yourdomain.com 并添加 nginx 以从您的域为 laravel 安装提供服务。com/laravel:

location ^~ /laravel {
    alias /pat/to/laravel/public;
    try_files $uri $uri/ @laravel;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

location @laravel {
    rewrite /laravel/(.*)$ /laravel/index.php?/ last;
}

如果您使用的是 Apache,请查看 Apache URL Rewriting Guide