Skip to main content

WordPress Import

<?php
function get_guids_for_posttype($post_type='post') : array {
	global $url;
	$command = 'wp --url=' . escapeshellarg( $url ) . ' post list --format=json --post_type=' . escapeshellarg( $post_type ) . ' --fields=ID,guid --porcelain';
	$json = rtrim( shell_exec( $command ), "\n" );
	if ( empty( $json ) ) {
		throw new RuntimeException( 'no guids' );
	}

	return json_decode( $json );
}

/**
 * Lookup post by guid.
 *
 * @param string $guid
 *
 * @return WP_Post|null
 */
function lookup_post_by_guid( string $guid ) : null|WP_Post {
	global $guids;
	global $_cache;
	$guid = str_replace( "&", "&#038;", $guid );
	if ( isset( $_cache[ $guid ] ) ) {
		return $_cache[ $guid ];
	}
	foreach ( $guids as $post ) {
		if ( $post->guid === $guid ) {
			$_cache[ $guid ] = $post;

			return $post;
		}
	}

	return null;
}