wp-ajax-api-diff
60 lines
<?php
<?php
add_action('wp_ajax_nopriv_get_products_from_api', 'get_products_from_api');
add_action('wp_ajax_nopriv_get_products_from_api', 'get_products_from_api');
add_action('wp_ajax_get_products_from_api', 'get_products_from_api');
add_action('wp_ajax_get_products_from_api', 'get_products_from_api');
function get_products_from_api() {
function get_products_from_api() {
$current_page = ( ! empty($_POST['current_page']) ) ? $_POST['current_page'] : 1;
$current_page = ( ! empty($_POST['current_page']) ) ? $_POST['current_page'] : 1;
$myproducts =[];
$myproducts =[];
$results = wp_remote_retrieve_body( wp_remote_get('https://link/to/api/endpoint/'));
$results = json_decode($results);
$results = wp_remote_retrieve_body( wp_remote_get('https://link/to/api/endpoint/'));
if ( ! is_array( $results ) || empty ( $results ) ) {
$results = json_decode($results);
return false;
}
$myproducts[] = $results;
$myproducts[] = $results;
foreach( $myproducts[0] as $myproduct ) {
foreach( $myproducts[0] as $myproduct ) {
$myproducts_slug = $myproduct->name;
$myproducts_slug = $myproduct->name;
$existing_product = get_page_by_path($myproducts_slug, 'OBJECT', 'myproduct');
$existing_product = get_page_by_path($myproducts_slug, 'OBJECT', 'myproduct');
if($existing_product === null ) {
if($existing_product === null ) {
$inserted_product = wp_insert_post([
$inserted_product = wp_insert_post([
'post_name' => $myproducts_slug,
'post_name' => $myproducts_slug,
'post_title' => $myproducts_slug,
'post_title' => $myproducts_slug,
'post_type' => 'myproducts',
'post_type' => 'myproducts',
'post_status' => 'publish'
'post_status' => 'publish'
]);
]);
if (is_wp_error($inserted_product) ) {
if (is_wp_error($inserted_product) ) {
continue;
continue;
}
}
//ADVANCED CUSTOM FIELDS INTEGRATION
//ADVANCED CUSTOM FIELDS INTEGRATION
$fillable = [
$fillable = [
'field_5dc862b619530' => 'name',
'field_5dc862b619530' => 'name',
'field_5dc862ec19531' => 'style',
'field_5dc862ec19531' => 'style',
'field_5dc863269b298' => 'description',
'field_5dc863269b298' => 'description',
'field_5dc8633738fad' => 'rating',
'field_5dc8633738fad' => 'rating',
];
];
foreach( $fillable as $key => $name ) {
foreach( $fillable as $key => $name ) {
update_field( $key, $myproducts->$name, $inserted_product );
update_field( $key, $myproducts->$name, $inserted_product );
}
}
}
}
}
$current_page = $current_page +1;
wp_remote_post(admin_url('admin-ajax.php?action=get_products_from_api'), [
'blocking' => false,
'sslverify' => false,
'body' => [
'current_page' => $current_page
]
]);
}
}