I am Nik Butler

Knowledge Knolling

WP CLI Fetching Posts, category, and terms

WP CLI : Fetching Posts, category, and terms

Following is an example of a script I assembled to export post information from wordpress and with it the categories and post_tags in use on the site at the time. Its ot the fastest answer but if you were looking to pull a report its possibly a useful example of what you can do .

#!/bin/bash
# list all posts
#  wp post list --fields=ID,post_parent,guid,post_status,post_title --format=csv
# fetch ids for
# wp post term list 11894 post_tag --fields=taxonomy,name,slug,term_taxonomy_id,term_id
# wp post term list 11894 category --fields=taxonomy,name,slug,term_taxonomy_id,term_id

WP_PATH=$1
WP_HEADER="ID,post_parent,guid,post_status,post_title"
TERM_HEADER="taxonomy,name,slug,term_taxonomy_id,term_id"
CSV_FIRSTLINE="${WP_HEADER},${TERM_HEADER}"

# Function to process a single post
process_post() {
  local id="$1"
  local rest_of_line="$2"
  local outputline="${id},${rest_of_line}"
  local tags=$(wp  --path=${WP_PATH} post term list "${id}" post_tag --fields=taxonomy,name,slug,term_taxonomy_id,term_id --format=csv 2> /dev/null| tail -n +2  )
  local categories=$(wp  --path=${WP_PATH} post term list "${id}" category --fields=taxonomy,name,slug,term_taxonomy_id,term_id  --format=csv   2> /dev/null | tail 


  -n +2  )
        while IFS=, read -r taxonomy name slug term_taxonomy_id term_id; do
                  echo "${outputline},post_tag,${name},${slug},${term_taxonomy_id},${term_id}"
        done <<< "$tags"

        while IFS=, read -r taxonomy name slug term_taxonomy_id term_id; do
          echo "${outputline},category,${name},${slug},${term_taxonomy_id},${term_id}"
        done <<< "$categories"
}

WP_POSTS=$(wp --path=${WP_PATH}  post list --fields=${WP_HEADER} --format=csv 2> /dev/null | tail -n +2  )


# Loop over remaining lines
while IFS=, read -r id rest_of_line
do
                # Check if id is empty
                if [ -z "$id" ]; then
                        continue
                fi

                if ! [[ "$id" =~ ^[1-9][0-9]*$ ]]; then
                        continue
                fi
                process_post "$id" "$rest_of_line"
done <<< "${WP_POSTS}"