Skip to content

Commit

Permalink
Merge pull request #449 from JulianBustamante/add/url-to-id-post-command
Browse files Browse the repository at this point in the history
Add command to get the post ID by URL
  • Loading branch information
swissspidy authored Nov 19, 2023
2 parents ce37f3c + b5f922e commit bc7f0e4
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3111,6 +3111,27 @@ wp post update <id>... [--post_author=<post_author>] [--post_date=<post_date>] [



### wp post url-to-id

Gets the post ID for a given URL.

~~~
wp post url-to-id <url>
~~~

**OPTIONS**

<url>
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.
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
"post term remove",
"post term set",
"post update",
"post url-to-id",
"post-type",
"post-type get",
"post-type list",
Expand Down
24 changes: 24 additions & 0 deletions features/post-url-to-id.feature
Original file line number Diff line number Diff line change
@@ -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.
"""
28 changes: 28 additions & 0 deletions src/Post_Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,34 @@ public function generate( $args, $assoc_args ) {
}
}

/**
* Gets the post ID for a given URL.
*
* ## OPTIONS
*
* <url>
* : 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 );
Expand Down

0 comments on commit bc7f0e4

Please sign in to comment.