Skip to content

Instantly share code, notes, and snippets.

@radist2s
Created November 4, 2018 20:35
Show Gist options
  • Save radist2s/dead72ff6357f5f5d4fa7023f2bfe109 to your computer and use it in GitHub Desktop.
Save radist2s/dead72ff6357f5f5d4fa7023f2bfe109 to your computer and use it in GitHub Desktop.
WP CLI Post generator helper
#/bin/bash
# Usage
# ./generate-posts.sh post_type [taxonomy_name count]
# post_type - Reqired
# taxonomy_name - Optional
# count - Optional
# Example:
# ./generate-posts.sh post # will create one post with thumnail and meta fields
# ./generate-posts.sh post category 4 # will create 4 posts and one existsing term appended for every post
THUMBS=""
TERMS=""
# add your fields here
post_fields() {
POST_ID=$1
post_add_meta $POST_ID job '[lllh words=4 /]'
post_add_meta $POST_ID job_description '[llle /]'
}
main() {
local readonly POST_TYPE=$1
local readonly COUNT=${2:-1}
local readonly TAX_NAME=$3
if [ -z "$POST_TYPE" ]; then
echo "No post type specified."
usage
exit 1
fi
for ((I=1; I <= $COUNT; I++)); do
generate_post $POST_TYPE $TAX_NAME
done
}
generate_post() {
local readonly POST_TYPE=$1
local readonly TAX_NAME=$2
echo "Creating Post of PostType=$POST_TYPE `if [ -n "$TAX_NAME" ]; then echo with term of Taxonomy=$TAX_NAME; fi`"
local readonly POST_ID=$(post_create $POST_TYPE)
post_fields $POST_ID
post_add_any_thumbnail $POST_ID
post_add_any_term $POST_ID $TAX_NAME
echo ID=$POST_ID
}
post_create() {
local readonly POST_TYPE=$1
echo "[lllc]" | wp post generate --format=ids --post_type=$POST_TYPE --count=1 --post_title="[lllh words=2 /]" --post_content
}
post_add_meta() {
ID=$1
KEY=$2
VALUE=$3
wp post meta add "$ID" "$KEY" "$VALUE"
}
post_add_any_thumbnail() {
post_add_meta $1 _thumbnail_id $(get_any_post_thumbnail_id)
}
post_add_any_term() {
POST_ID=$1
TAX=$2
if [ -z "$TAX" ]; then
return
fi
TERM_ID=$(get_any_taxonomy_term_id $TAX)
wp eval "wp_set_object_terms($POST_ID, [$TERM_ID], '$TAX');"
}
get_any_post_thumbnail_id() {
if [ -z "$THUMBS" ]; then
THUMBS=($(get_attachment_ids))
fi
echo ${THUMBS[$RANDOM % ${#THUMBS[@]}]}
}
get_any_taxonomy_term_id() {
TAX=$1
if [ -z "$TERMS" ]; then
TERMS=($(get_taxonomy_term_ids $TAX))
fi
echo ${TERMS[$RANDOM % ${#TERMS[@]}]}
}
get_attachment_ids() {
limit=${1:--1}
wp post list --post_type=attachment --post_mime_type="image/jpeg" --posts_per_page=$limit --format=ids
}
get_taxonomy_term_ids() {
wp term list $1 --format=ids
}
usage() {
ME=$(basename "$0")
echo "Usage:"
echo "$ME post_type taxonomy_name count"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment