Update Post Templates with WP CLI

June 14, 2018 - posted by Josh Smith

Sometimes you want to update your WordPress one post template at a time. Luckily, you can update custom post type templates easily with WP CLI commands.wp-cli logo

I added a new post template to my own site recently. It was already a Custom Post Type, but the CPT was basically only used as a differentiator of data, which is a good thing. When you think about your data it should have structure and Custom Post Types are one way to achieve that structure. Once you have the data structure you may want to display that data in a specific way. You can create a new template called single-{post_type}.php. When I created the template for mine, I simply copied the existing single.php and removed the sidebar no big deal. Then I had to finish the change in the databas3e with a bulk operation from WP-CLI.

The command I used is actually a combination of commands. I’ll explain below.

wp post update $( wp post list --category_name=<post_category> --format=ids ) --post_type=<post_type>

When you see the $() it means to return the results of that command to the whatever called it. In this case, wp post update called it. wp post update also takes in two options; what you’re changing and what you’re changing it to. In my case, I wanted to get all the posts that I was using that had a category of special. I would then change those posts to their own post type.

wp post update $( wp post list --category_name=special --format=ids ) --post_type=special

Now, I can display my new posts with their own template file of single-special.php.

 

 

© 2019 All Rights Reserved

Designed by Josh at Efficiency of Movement