• Hi,
    I have more than 50 sites on the same server.
    I wrote a separate PHP script which will gather post and try to add them into all 50 wordpress site’s databases.
    I am using wp_insert_post() to insert the post into the database.
    But it only insert all the posts to first wordpress site.
    Can anyone please tell me how i can change the database connection at run time so i can insert one article to all my wordpress databases using wp_insert_post() function.

    I will be very thankful.

Viewing 5 replies - 1 through 5 (of 5 total)
  • It should be relatively easy. All that you’d need to do is loop through each site, grab the wp-config file from that for the settings, apply those settings, save the post, then move on to the next site. As for actual code… that’s a very big job, so it’s not something that I want to try and do on here.

    Thread Starter usman172

    (@usman172)

    Hello Michael,
    Thank you for your reply.
    I have already tried this but it don’t work. because in the config.php they have defined the constant of db information so next time it is not resetting the DB values.It insert all the records in the first database.
    By the way i have fixed this issue.
    We can handle this thing by using the information of root database through which we can access all the databases and then we can simple use the

    $wpdb->select(‘database_name’);
    $wpdb->flush(); to clear SQL result cache with flush

    And this worked for me.

    I didn’t mean that you should just include the files. I knew that they’d create problems due to the constants already being defined. Sorry for the confusion there, I shoud have explained more. ??

    What I meant was…

    Loop through the wp-config files, and read them in as plain text, and parse this text form within your own PHP script to pull out the database connection values. it’s not to hard to do with some string matching and regex work. That way you can get the values that you want and set up the new connections.

    If I am right, what you’ve done nos is jsut give the main DB user write privilidges on each of the DB’s? That works fine, and hopefull ywil continue to it. The only time I can see an issue is if you ever have a database that’s not set on the same server.

    Thread Starter usman172

    (@usman172)

    Yes Michael,

    I agree with you. It will create problem when DB will be on a separate server.
    Right now databases are on the same server, when they will be on different server then i will go for you solution.

    Again thank you for my help.

    Personally, I’d just edit wp-load.php.

    It tells WP to load wp-config.php. You could add in any of the swapping logic and switch to whichever config file you need.

    If that doesn’t work for you, I am available to write you a plugin to swap data between databases.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Change database conenction at tun time.’ is closed to new replies.