问题描述

我有一个 PHP 脚本,我需要作为一个 cron 作业运行。但是该脚本需要访问 WP API(get_pages()get_post_meta()get_permalink()) 。我按照 http://codex.wordpress.org/Integrating_WordPress_with_Your_Website 的说明进行操作,但无效。

码:

require_once('../../../wp-blog-header.php');
$args = array(
    'child_of' => 2083
);
$pages = get_pages($args);

但是当我从命令行运行 php -q this_file.php 时,我得到以下输出:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Database Error</title>

</head>
<body>
    <h1>Error establishing a database connection</h1>
</body>
</html>

任何人有任何想法/建议?

最佳解决方案

WordPress 希望 $ _SERVER 变量被设置为一般的 Web 请求。此外,我建议加载 wp-load.php 而不是 wp-blog-header.php,因为你可能不需要 WP 类或模板加载器来运行。以下是我通常从命令行开始任何需要与 WP 进行交互的脚本:

define('DOING_AJAX', true);
define('WP_USE_THEMES', false);
$_SERVER = array(
    "HTTP_HOST" => "mysite.com",
    "SERVER_NAME" => "mysite.com",
    "REQUEST_URI" => "/",
    "REQUEST_METHOD" => "GET"
);
require_once('current/wp-load.php');

次佳解决方案

您可以使用 wp-cli eval-file 命令:

@daily /usr/bin/wp --path=/path/to/wp/ eval-file /path/to/that_file.php

这将首先加载 WP 环境,然后运行您的文件。

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。