Skip to content

Instantly share code, notes, and snippets.

@michael-sumner
Created April 21, 2023 15:51
Show Gist options
  • Save michael-sumner/8856968878468b8c0f3f42535cd672e7 to your computer and use it in GitHub Desktop.
Save michael-sumner/8856968878468b8c0f3f42535cd672e7 to your computer and use it in GitHub Desktop.
The script uses WP-CLI to add a tag with specified ID to all posts published in the year 2022. It first gets a list of post IDs for the year 2022 and then loops through each post ID to add the tag. The script is useful for quickly adding a tag to a large number of posts without manual editing in the WordPress admin interface.
#!/bin/bash
###
# The script uses wp post list command to get a list of post IDs from the year 2022 and saves them in a file called post_ids.txt. It then loops through each post ID in the file and adds the tag with ID 47365 to the post using the wp post term add command with the post_tag taxonomy.
# Please note that you need to have the post_tag taxonomy registered for posts in your WordPress site and you may need to replace 47365 with the actual ID of the tag you want to add.
#
# Save the script with a filename like add_tag_to_2022_posts.sh, make it executable using the chmod +x add_tag_to_2022_posts.sh command, and run it by executing ./add_tag_to_2022_posts.sh in your terminal.
###
# Get all posts from the year 2022
wp post list --field=ID --post_type=post --date_query="year=2022" > post_ids.txt
# Loop through the post IDs and add tag id 47365
while read -r post_id; do
wp post term add $post_id post_tag 47365 --by=id
done < post_ids.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment