我正在尝试编写一个循环,该循环将发布来自SQL数据库的文章。然而,每当我尝试加载页面时,都会出现500个错误,错误日志中没有显示任何内容。
代码:
<?php
define(\'WP_USE_THEMES\', false);
require(\'wp-load.php\');
global $wpdb;
$sql = "SELECT * FROM newposts";
$result = $wpdb->query($sql);
while($row = $result->fetch_assoc()) {
$post = array(
\'post_title\' => $row[\'post_title\'],
\'post_content\' => $row[\'post_content\'],
\'post_date\' => $row[\'post_date\'],
\'post_status\' => \'publish\',
\'post_author\' => 1,
\'post_category\' => 1
);
wp_insert_post( $post );
echo "inserted post {$row[\'post_title\']}";
echo "<br />";
}
?>
我是wordpress的新手,所以我不知道我是否正确使用了$wpdb或插入post函数。此外,该文件与wp load、wp config等放在同一目录中,并且该站点正在bluehost上运行,如果这意味着什么的话(我不知道)。
谢谢你的时间!
最合适的回答,由SO网友:Ismail 整理而成
这是因为您试图定义一个已经定义的属性,查询一个名称错误的表,循环一个整数,而您可以使用get_results
而不是query
方法$wpdb
...
我编辑了代码,希望它对您的复制后处理有所帮助:
defined( \'WP_USE_THEMES\' ) || define( \'WP_USE_THEMES\', false );
require_once(\'wp-load.php\');
global $wpdb;
$sql = "SELECT * FROM {$wpdb->prefix}newposts";
$result = $wpdb->get_results( $sql );
foreach ( $result as $row ):
$row = ( array ) $row;
$post = array(
\'post_title\' => $row[\'post_title\'],
\'post_content\' => $row[\'post_content\'],
\'post_date\' => $row[\'post_date\'],
\'post_date_gmt\' => $row[\'post_date_gmt\'],
\'post_status\' => \'publish\',
\'post_author\' => 1,
\'post_category\' => array(1)
);
wp_insert_post( $post );
echo "inserted post {$row[\'post_title\']}";
echo "<br />";
endforeach;