How to manage Wordpress posts using WP-CLI

In our last article we went thru some wp-cli usage examples and got a bit familiar with the wp-cli tool. In this article we will see how we can manage our posts using the wp-cli tool.

The basic syntax is :

wp post <command

SUBCOMMANDS

  create        Create a post.
  delete        Delete a post by ID.
  edit          Launch system editor to edit post content.
  generate      Generate some posts.
  get           Get a post's content by ID.
  list          Get a list of posts.
  meta          Manage post custom fields.
  term          Manage post terms.
  update        Update one or more posts.

 So let us give some examples of the most common and useful post activities using the wp-cli tool.

How to list all the posts in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post list

How to list all the posts for a specific user in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post --user=1 list

How to create new post in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post create --post_status=publish --post_title="Test AO Post" --edit

Success: Created post 5475.

How to edit a post in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post edit 5475
Warning: No change made to post content.

How to change the wp-cli editor

  • you can choose your preffred editor, the only thing you need to do is added in your .bashrc file.
export EDITOR=vim
Assuming vim is your editor of choice

How to delete a post in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post delete 5475 --force

Success: Deleted post 5475.

How to delete all posts from the trash in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post delete $(wp post list --post_status=trash --format=ids)

Success: Deleted post 5223.

How to update the Name a post in Wordpress using WP-CLI

We will update the post name.
aodba451@sgp25 [~/www]#wp post update 5477 --post_name='New Name Post' --post_status=publish

    Success: Updated post 5477.	

How to update the Title of a post in Wordpress using WP-CLI

aodba451@sgp25 [~/www]# wp post update 5477 --post_title="New Title Post"

Success: Updated post 5477.
Still wanna know more about WP-CLI ? Read the next article on what are the database operations we can do with WP-CLI.