diff --git a/README.md b/README.md index 2a53377d..e497ca6a 100644 --- a/README.md +++ b/README.md @@ -3111,6 +3111,27 @@ wp post update ... [--post_author=] [--post_date=] [ +### wp post url-to-id + +Gets the post ID for a given URL. + +~~~ +wp post url-to-id +~~~ + +**OPTIONS** + + + The URL of the post to get. + +**EXAMPLES** + + # Get post ID by URL + $ wp post url-to-id https://example.com/?p=1 + 1 + + + ### wp post-type Retrieves details on the site's registered post types. diff --git a/composer.json b/composer.json index 40a75742..1bef351b 100644 --- a/composer.json +++ b/composer.json @@ -115,6 +115,7 @@ "post term remove", "post term set", "post update", + "post url-to-id", "post-type", "post-type get", "post-type list", diff --git a/features/post-url-to-id.feature b/features/post-url-to-id.feature new file mode 100644 index 00000000..cb9ddf9e --- /dev/null +++ b/features/post-url-to-id.feature @@ -0,0 +1,24 @@ +Feature: Get the post ID for a given URL + + Background: + Given a WP install + + Scenario: Get the post ID for a given URL + When I run `wp post get 1 --field=url` + Then STDOUT should be: + """ + https://example.com/?p=1 + """ + And save STDOUT as {POST_URL} + + When I run `wp post url-to-id {POST_URL}` + Then STDOUT should contain: + """ + 1 + """ + + When I try `wp post url-to-id 'https://example.com/?p=404'` + Then STDERR should contain: + """ + Could not get post with url https://example.com/?p=404. + """ \ No newline at end of file diff --git a/src/Post_Command.php b/src/Post_Command.php index 43429594..9d6e040a 100644 --- a/src/Post_Command.php +++ b/src/Post_Command.php @@ -878,6 +878,34 @@ public function generate( $args, $assoc_args ) { } } + /** + * Gets the post ID for a given URL. + * + * ## OPTIONS + * + * + * : The URL of the post to get. + * + * ## EXAMPLES + * + * # Get post ID by URL + * $ wp post url-to-id https://example.com/?p=1 + * 1 + * + * @subcommand url-to-id + */ + public function url_to_id( $args, $assoc_args ) { + $post_id = url_to_postid( $args[0] ); + + $post = get_post( $post_id ); + + if ( null === $post ) { + WP_CLI::error( "Could not get post with url $args[0]." ); + } + + WP_CLI::print_value( $post_id, $assoc_args ); + } + private function maybe_make_child() { // 50% chance of making child post. return ( wp_rand( 1, 2 ) === 1 );