How to run wp_insert_post() & wpdb on the background?
I have created a code to fetch data from a remote API then echo certain data import those data into a post type using wp_insert_post()
post meta** using wpdb-query()
.
Here's my current code:
$imdbid = $_GET['id'];
$string = file_get_contents(http://www.omdbapi.com/?i=.$imdbid.apikey=API_KEY_HEREKEYVALUE);
$json = json_decode($string, true);
if( $json['Response'] === True ){
//METADATA
$dataID = $json['imdbID'];
$dataTitle = $json['Title'];
$dataYear = $json['Year'];
$dbdata = array(
'post_title' = $dataID,
'post_status' = 'publish',
'post_type' = 'datadb',
'post_author' = 1
);
if( $dbid = wp_insert_post( $dbdata ) ){
//METADATA PRINT
echo $dataID;
echo $dataTitle;
echo $dataYear;
$statement = INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
('.$dbID.', 'ztdb_imdb_id', '%s'),
('.$dbID.', 'ztdb_title', '%s'),
('.$dbID.', 'ztdb_year', '%s');;
$sql = $wpdb-prepare($statement, $dataID, $dataTitle, $dataYear);
$wpdb-query($sql);
}
}
Right now, if i use just these codes, the page would not stop loading until wp_insert_post()
and wpdb
is completed. Is there any way I could run both of them on the background so the user's page load is not affected when visiting the page and the $dataID, $dataTitle, and $dataYear is echoed/displayed immediately?