Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add command to get the post ID by URL #449

Merged
merged 7 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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