You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中获取子目录下WordPress的当前登录用户信息

问题解决方案

冲突原因

Laravel 与 WordPress 均定义了全局翻译帮助函数 __(),直接在服务提供者中加载 wp-load.php 会触发函数重复声明报错。

方案一:兼容加载WordPress核心(可调用全量WP功能)

直接修改你编写的 WordPressServiceProvider 代码即可:

<?php
 
namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
use URL;
 
class WordPressServiceProvider extends ServiceProvider
{
    // 修改为Laravel官方路径函数,适配所有操作系统
    protected $bootstrapFilePath;

    public function __construct($app)
    {
        parent::__construct($app);
        $this->bootstrapFilePath = public_path('shop/wp-load.php');
    }

    public function boot()
    {
        // 此处可以正常调用WP的方法,比如判断登录状态
        // dd(is_user_logged_in());
    }
 
    public function register()
    {   
        if(\File::exists($this->bootstrapFilePath)) {
            // 提前将Laravel原生__()方法存为别名
            if (!function_exists('laravel__')) {
                function laravel__(...$args) {
                    return __(...$args);
                }
            }
            // 提前声明__()方法,阻止WordPress重复定义
            if (!function_exists('__')) {
                function __(...$args) {
                    // 优先使用Laravel的翻译逻辑,有WP翻译需求可自行调整
                    return laravel__(...$args);
                }
            }
            // 加载WordPress核心
            require_once($this->bootstrapFilePath);
            // 给WordPress原生翻译方法注册别名,需要时可调用
            if (!function_exists('wp__')) {
                function wp__(string $text, string $domain = 'default') {
                    return apply_filters('gettext', $text, $text, $domain);
                }
            }
        }
    }
}

使用说明:

  • 原有Laravel的__()翻译方法不受影响
  • 需要调用WordPress的翻译功能时,使用wp__()方法即可
  • 所有WordPress原生函数都可以正常调用,比如is_user_logged_in()、wp_get_current_user()等

方案二:轻量获取登录用户(无任何函数冲突)

如果你只需要获取WordPress登录用户信息,不需要调用其他WordPress功能,推荐用这个方案,完全不需要加载WP核心文件:

  1. 首先在config/database.php中新增WordPress数据库连接配置(如果WP和Laravel共用数据库可以跳过这步)
  2. 直接编写工具方法解析WP登录Cookie获取用户信息:
// 可放在app/Helpers目录下全局调用
function getCurrentWpUser()
{
    // 替换为你站点的WP登录Cookie名,可从浏览器开发者工具的Cookie列表中复制,前缀为wordpress_logged_in_
    $wpLoggedCookie = 'wordpress_logged_in_xxxxxxxxx';
    if (empty($_COOKIE[$wpLoggedCookie])) return null;

    $cookiePieces = explode('|', $_COOKIE[$wpLoggedCookie]);
    if (count($cookiePieces) < 3) return null;

    $userId = intval($cookiePieces[0]);
    // 可自行补充Cookie签名校验逻辑,校验通过后查询用户数据
    return \DB::connection('wordpress')->table('users')->where('ID', $userId)->first();
}

这个方案性能更高,不会引入任何WordPress和Laravel的功能冲突。

内容的提问来源于stack exchange,提问作者kantsverma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:06:03