Skip to content

Instantly share code, notes, and snippets.

@kjtolsma
Created April 5, 2023 08:50
Show Gist options
  • Save kjtolsma/b9718a7b17dcbc768e7ba855e31ba8ea to your computer and use it in GitHub Desktop.
Save kjtolsma/b9718a7b17dcbc768e7ba855e31ba8ea to your computer and use it in GitHub Desktop.
/**
* Import
*/
class Import {
/**
* Construct
*/
public function __construct() {
\add_action( 'init', [ $this, 'schedule_imports' ] );
\add_action( 'import_schedule_task', [ $this, 'sync_posts' ] );
}
/**
* Check if posts exists
*
* @param string $field Value of field
*/
public function post_exists( $field ) {
global $wpdb;
$query = "
SELECT
post_id
FROM
$wpdb->postmeta
WHERE
meta_key = %s
AND
meta_value = %s
";
$id = (int) $wpdb->get_var(
$wpdb->prepare(
$query,
[
'connected_post_id',
$field
]
)
);
return $id;
}
/**
* Schedule imports
*
* @param int $page Number of page
*/
public function do_import() {
if ( ! isset( $_GET['sync'] ) ) {
return;
}
$number_of_pages = 2; // Get from remote request header.
for ( $i = 1; $i <= $number_of_pages; $i++ ) {
$this->sync_posts( $i );
// Action
\as_enqueue_async_action(
'import_schedule_task',
[ $page ]
);
}
}
/**
* Get posts
*
* @param int $page Number of page
*/
public function get_posts( $page = 1 ) {
$remote_url = \add_query_arg(
'page',
$page,
'https://staging.gidsen.daadkracht-marketing.nl/api/companies'
);
$token = 'Syz2AEgpdO5aIfnf0e7firyWX2uj0DUWk1QJ9UMJ';
$args = [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
];
$response = \wp_remote_get( $remote_url, $args );
if ( \is_wp_error( $response ) ) {
return;
}
if ( 200 !== \wp_remote_retrieve_response_code( $response ) ) {
return;
}
$results = \json_decode( $response['body'] );
return $results;
}
/**
* Sync posts
*
* @param int $page
*/
public function sync_posts( $page = 1 ) {
$posts = $this->get_posts( $page );
if ( empty( $posts ) ) {
return;
}
foreach ( $posts as $post ) {
$id = $post->id;
$name = $post->name;
if ( ! $id || ! $name ) {
continue;
}
// Post arguments
$meta_input = [
'connected_post_id' => $id,
];
$args = [
'post_type' => 'page',
'post_title' => $name,
'post_status' => 'publish',
'meta_input' => $meta_input,
];
// Check if there is already an event present.
$post_id = $this->post_exists( $id );
// Update or add new post.
if ( $post_id ) {
$args['ID'] = $post_id;
\wp_update_post( $args );
} else {
$post_id = \wp_insert_post( $args );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment