Skip to content

Commit bc7f0e4

Browse files
authored
Merge pull request #449 from JulianBustamante/add/url-to-id-post-command
Add command to get the post ID by URL
2 parents ce37f3c + b5f922e commit bc7f0e4

File tree

4 files changed

+74
-0
lines changed

4 files changed

+74
-0
lines changed

README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3111,6 +3111,27 @@ wp post update <id>... [--post_author=<post_author>] [--post_date=<post_date>] [
31113111

31123112

31133113

3114+
### wp post url-to-id
3115+
3116+
Gets the post ID for a given URL.
3117+
3118+
~~~
3119+
wp post url-to-id <url>
3120+
~~~
3121+
3122+
**OPTIONS**
3123+
3124+
<url>
3125+
The URL of the post to get.
3126+
3127+
**EXAMPLES**
3128+
3129+
# Get post ID by URL
3130+
$ wp post url-to-id https://example.com/?p=1
3131+
1
3132+
3133+
3134+
31143135
### wp post-type
31153136

31163137
Retrieves details on the site's registered post types.

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@
115115
"post term remove",
116116
"post term set",
117117
"post update",
118+
"post url-to-id",
118119
"post-type",
119120
"post-type get",
120121
"post-type list",

features/post-url-to-id.feature

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Feature: Get the post ID for a given URL
2+
3+
Background:
4+
Given a WP install
5+
6+
Scenario: Get the post ID for a given URL
7+
When I run `wp post get 1 --field=url`
8+
Then STDOUT should be:
9+
"""
10+
https://example.com/?p=1
11+
"""
12+
And save STDOUT as {POST_URL}
13+
14+
When I run `wp post url-to-id {POST_URL}`
15+
Then STDOUT should contain:
16+
"""
17+
1
18+
"""
19+
20+
When I try `wp post url-to-id 'https://example.com/?p=404'`
21+
Then STDERR should contain:
22+
"""
23+
Could not get post with url https://example.com/?p=404.
24+
"""

src/Post_Command.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -878,6 +878,34 @@ public function generate( $args, $assoc_args ) {
878878
}
879879
}
880880

881+
/**
882+
* Gets the post ID for a given URL.
883+
*
884+
* ## OPTIONS
885+
*
886+
* <url>
887+
* : The URL of the post to get.
888+
*
889+
* ## EXAMPLES
890+
*
891+
* # Get post ID by URL
892+
* $ wp post url-to-id https://example.com/?p=1
893+
* 1
894+
*
895+
* @subcommand url-to-id
896+
*/
897+
public function url_to_id( $args, $assoc_args ) {
898+
$post_id = url_to_postid( $args[0] );
899+
900+
$post = get_post( $post_id );
901+
902+
if ( null === $post ) {
903+
WP_CLI::error( "Could not get post with url $args[0]." );
904+
}
905+
906+
WP_CLI::print_value( $post_id, $assoc_args );
907+
}
908+
881909
private function maybe_make_child() {
882910
// 50% chance of making child post.
883911
return ( wp_rand( 1, 2 ) === 1 );

0 commit comments

Comments
 (0)