简体   繁体   中英

wp_insert_post from other MYSQL DB, getting wordpress error

I am trying to move website to wordpress from other CMS. I have access to mySql DB of this old CMS. So I am trying to get news from old website to new web site. This is my code:

<?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.'">';

When I am start this code, I get WP_Error - "Couldn't insert to database". But I can't understand, what's wrong. Please help, if you can :)

我解决了这个问题,当删除此行$ dbh-> query(“ SET NAMES'cp1251'”);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM