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?

Topic wp-insert-post wp-cron cron wpdb Wordpress

Category Web


page load is not affected [...] and the //METADATA is echoed/displayed immediately?

With your current setup, that is not possible. In order to display immediately, you need the data. To get the data, you need to wait.

Possible solutions are:

  1. Fetch the data before (e.g. via Cron) and populate the DB with the info. -> No need to fetch it live, but you might not know, which ids to get and which not to.

  2. Fetch the data asynchronous (e.g. via calling a REST endpoint in the template). -> Page will load fast, but parts are missing and rendered later. No need to pre-fetch the data though.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.