• Hi All,

    Are there ways to write wordpress plugin to save a new post to some other wordpress database table.

    Actually, hooks from wordpress allow a code to fire up only after the new post is created in wordpress wp_posts table.

    But I would like to know if there are ways to make when the user adds a new post and hits publish receive all wordpress data and insert all data to some other mySQL Table.

    Thank you!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Yes, but it must be done in a carefully thought out manner. Unless the DBs are exact mirrors, the clone post will likely have a different ID than the native post. It could be necessary to maintain a relationship between the IDs so when the native post is altered the correct clone can likewise be altered.

    You can connect to another DB using the ‘wpdb’ class, creating a new instance just like the global $wpdb object. You can directly manipulate the other DB through class methods, or juggle which instance is currently in the global $wpdb so that native WP functions can be used to insert posts in the other DB.

    For example, we hook the ‘save_post’ action which fires after a post is saved. Our callback swaps the ‘wpdb’ objects, then calls wp_insert_post() to insert the same post in the other DB, then swaps the ‘wpdb’ objects back again to restore normal operation. Swapping of posts IDs as maintained in a custom table or native post meta would also need to occur.

    Our callback must also remove itself from the ‘save_post’ action so that when wp_insert_post() is called again, our callback is not re-entered, starting an infinite loop. Just before returning we can add our callback back in to be ready for the next save post action.

Viewing 1 replies (of 1 total)
  • The topic ‘way for adding new post to go to custom database table’ is closed to new replies.