wordpress - 如何在自定义 php 文件中使用 wordpress 的功能
问题描述
我在包含 wp-load.php 的自定义 php 文件中使用函数 have_posts() 。但我有这个错误:
致命错误:在第 767 行的 C:\xampp\htdocs\khanehkheshti\wp-includes\query.php 中调用一个成员函数 have_posts() on null
.php 文件:
require_once( wp_normalize_path(ABSPATH).'wp-load.php');
public static function home() {
$query = new WP_Query(array(category_name => "img_news", 'posts_per_page' => '3' ));
$home = array();
$in = array();
while ( $query->have_posts() ) {
$query->the_post();
$home['title'] = get_the_title();
$home['content'] = get_the_content();
$home['img'] = the_post_thumbnail( array( 300, 260 ) );
$in[] = $home;
}
echo JSON_encode($in);
return $in;
}
解决方案
尝试用 wp-blog-header.php 替换 wp-load.php。这是示例代码:
define('WP_USE_THEMES', false);
require_once('PATHHERE/wp-blog-header.php');
public static function home() {
$query = new WP_Query(array(category_name => "img_news", 'posts_per_page' => '3' ));
$home = array();
$in = array();
while ( $query->have_posts() ) {
$query->the_post();
$home['title'] = get_the_title();
$home['content'] = get_the_content();
$home['img'] = the_post_thumbnail( array( 300, 260 ) );
$in[] = $home;
}
echo JSON_encode($in);
return $in;
}
推荐阅读
- sql - case 语句返回 0 而不是空字符串
- python-3.x - str.split() 是否容易受到拒绝服务攻击?
- c# - 如何创建只接受数字和布尔值的动态类型变量?
- python-3.x - 合并时如何使用 GitPython 使用“--no-ff --no-commit”?
- visual-studio - 将 csproj 文件配置移动到其他文件
- c# - 仅将所需的存储过程添加到 EDMX
- android - Flutter 预缓存图像
- c++ - 我想更改变量值,但我想要的内存地址将保持不变,我该怎么做
- sql - Oracle 11g:插入记录时出现 ORA-00604 ORA-02429。无法插入表格
- .net - 部署警告 SQL46010:发布 SQL Server 项目时,.. 附近的语法不正确