来自其他MYSQL DB的wp_insert_post,导致wordpress错误

时间:2016-08-18 13:47:59

标签: php mysql wordpress

我正在尝试将网站从其他CMS移到wordpress。我可以访问这个旧CMS的mySql DB。所以我试图从旧网站获取新网站的新闻。这是我的代码:

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);



$hostname = "XXX.XX.XXX.XX";
$username = "myusername";
$password = "mypassw";
$dbName = "mydb";

$root = 2;  //category on old website
$thema = 10; //subcategory on old website

$category = 17; //category on new website with wordpress

$enabled = '1'; //only enabled new on old website
$user_id = 1; //admin id in wordpress


$all = 0;


if(isset($_GET['offset']) && isset($_GET['all']))
{
    $offset = $_GET['offset'];
    $all = $_GET['all'];
}else{
    $offset = 0;

    //Getting number of all news...
    try {
        $dbh = new PDO('mysql:host='.$hostname.';dbname='.$dbName, $username, $password);
        foreach($dbh->query("SELECT * FROM `news` WHERE `root` = ".$root." AND `thema` = ".$thema." AND `enabled` = '1'") as $row) {
            $all++;
        }
        $dbh = null;
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
}
if($offset>$all)
{
    echo "Ready...";
    exit();

}

echo "All:".$all."<BR>";


    try {
        $dbh = new PDO('mysql:host='.$hostname.';dbname='.$dbName, $username, $password);
        $dbh->query("SET NAMES 'cp1251'");
        foreach($dbh->query("SELECT * FROM `news` WHERE `root` = ".$root." AND `thema` = ".$thema." AND `enabled` = '1' ORDER BY `news`.`id` ASC LIMIT ".$offset.", 30 ") as $row) {

            $new_post = array(
              'post_title' => $row['title'],
              'post_content' => $row['text'],
              'post_status' => 'publish',
              'post_date' => date('Y-m-d H:i:s', $row['created']),
              'post_author' => 1,
              'post_type' => 'post',
              'post_category' => array($category)
            );

            $post_id = wp_insert_post($new_post, true); //insert post (returns 0)

            echo "<pre>";
                print_r($post_id);
            echo "</pre>";

            echo $_POST['title']."<BR>done...<BR>";     
        }
        $dbh = null;
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }


$offset = $offset + 31;
echo 'wait..<meta http-equiv="refresh" content="5; url=get.php?offset='.$offset.'&all='.$all.'">';

当我启动此代码时,我得到WP_Error - &#34;无法插入数据库&#34;。 但是我无法理解,这是错误的。 请帮助,如果可以:)

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,当删除这行$ dbh-&gt;查询(“SET NAMES'cp1251'”);