Wp post meta get (WP-CLI)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

wp post meta get: Retrieve complete content of a particular meta object:

  • This works for both scalars and serialized data.
  • If you want to get the value of a (serialized) nested value: Use wp post meta pluck.
$ wp help post meta get

NAME

  wp post meta get

DESCRIPTION

  Get meta field value.

SYNOPSIS

  wp post meta get <id> <key> [--format=<format>]

OPTIONS

  <id>
    The ID of the object.

  <key>
    The name of the meta field to get.

  [--format=<format>]
    Get value in a particular format.
    ---
    default: var_export
    options:
      - var_export
      - json
      - yaml
    ---

Basic example

#
# See all meta objects home page (id=7)
########################################
#
wp post meta list 7   # OK


# Retrieve value with "list"
########################################
#
# This is the first serialised field in the list
#
wp post meta list 7 --keys="hero_ctas_0_link"   # OK


# Retrieve object with "get"
########################################
#
# * Syntaxis is now without "--keys"
# * This works with or without double quotes
#
wp post meta get 7 "hero_ctas_0_link"   # OK
wp post meta get 7 hero_ctas_0_link	# OK

Output of any of the last get statements:

array (
  'title' => 'Bekijk alle widgets',
  'url' => 'http://en.s1/shop/',
  'target' => '',
)

Variables in arguments

All these lines work and yield identical results:

id=7
bb=3
wp post meta get 7 buttonbars_3_buttonbar_title
wp post meta get 7 buttonbars_${bb}_buttonbar_title
wp post meta get $id buttonbars_${bb}_buttonbar_title

Check for the existence of an attachment

Use case: A script to update alt texts of images. Along the way, first check if the given post id actually corresponds to an image.

Examples:

#
# Post-id refers to an image
#####################################
#
$ wp post meta get 62808 _wp_attached_file

2021/06/4611-0283_3-LOGO.jpg


# post-id doesn't exist
#####################################
#
$ wp post meta get 63948 _wp_attached_file

Error: Could not find the post with ID 63948.


# post-id exists, but isn't an image
#####################################
#
$ wp post meta get 7 _wp_attached_file

# No output

→ Maybe easier to check for the post type: Wp post get (WP-CLI)

See also