I have a plugin which creates a new database table. Upon activating the plugin is there a way to insert all my posts ids into that table?
Right now I’m using an action hook to immediately insert the id of new posts I publish.
function transfer_post_id($post_ID) {
global $wpdb;
if (!($wpdb->get_row("SELECT post_id FROM $my_table WHERE post_id = $post_ID" ) ) ) { //if post id not already added
$wpdb->insert( $my_table, array( 'post_id' => $post_ID ) );
}
return $post_ID;
}
add_action ( 'publish_post', 'transfer_post_id' );
However there are posts before activating the plugin that I need a way to insert without manually updating each one.
3 Answers
Like so:
INSERT INTO $mytable (post_id)
SELECT ID
FROM $wpdb->posts as posts
LEFT JOIN $mytable as dup_check
ON dup_check.post_id = posts.ID
WHERE dup_check.post_id IS NULL;