Skip to content

Add a flag for getting post meta as a single value or not #523

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

Merged
merged 8 commits into from
Feb 27, 2025
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
33 changes: 33 additions & 0 deletions features/post-meta.feature
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,39 @@ Feature: Manage post custom fields
My\New\Meta
"""

Scenario: List post meta with or without single flag
Given a WP install

When I run `wp post meta add 1 apple banana`
And I run `wp post meta add 1 apple mango`
Then STDOUT should not be empty

When I run `wp post meta get 1 apple`
Then STDOUT should be:
"""
banana
"""

When I run `wp post meta get 1 apple --single`
Then STDOUT should be:
"""
banana
"""

When I run `wp post meta get 1 apple --no-single`
Then STDOUT should be:
"""
array (
0 => 'banana',
1 => 'mango',
)
"""
When I run `wp post meta get 1 apple --no-single --format=json`
Then STDOUT should be:
"""
["banana","mango"]
"""

@pluck
Scenario: Nested values can be retrieved.
Given a WP install
Expand Down
6 changes: 5 additions & 1 deletion src/WP_CLI/CommandWithMeta.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ function ( $a, $b ) use ( $orderby, $order ) {
* <key>
* : The name of the meta field to get.
*
* [--single]
* : Whether to return a single value.
*
* [--format=<format>]
* : Get value in a particular format.
* ---
Expand All @@ -156,8 +159,9 @@ public function get( $args, $assoc_args ) {
list( $object_id, $meta_key ) = $args;

$object_id = $this->check_object_id( $object_id );
$single = Utils\get_flag_value( $assoc_args, 'single', true );

$value = $this->get_metadata( $object_id, $meta_key, true );
$value = $this->get_metadata( $object_id, $meta_key, $single );

if ( '' === $value ) {
die( 1 );
Expand Down