I need to change the template on several hundred pages on my site. Does anyone know if there is a command to do it programmatically? See the following code snippet; I’d like to replace my comment inside the loop with a function that will change the template of the current page:
query = new WP_Query($args);
while ( $query->have_posts() ) : $the_query->the_post();
if ( has_tag('tag-slug') )
{
/* CHANGE TEMPLATE OF $post */
}
endwhile;
wp_reset_postdata();
I take it that you mean saving the pages with a new post-template to the DB? see if there’s anything in the post object that refers to the page-template, if so craft a query that updates that.
Update:
So you can fetch the page template using get_post_meta, and update it with update_post_meta (Or set it with add_post_meta)
What kinds of formatting are you referring to? If you want to change the formatting that can be changed by css. You can use post_class() which will add a class naming your tag in the container. Then you can style targeting that class.
Inside the loop:
Also check the action pre_get_post; Using it with conditionals might help.
Try this:
You would then need to create
content.php
andcontent-tag-slug.php
with the appropriate content.You could also look into setting up Post Formats. A bit more work up front, but a nicer experience down the road.
To change the template of a post, call
update_post_meta($query->the_post->ID, '_wp_page_template', 'YOUR-NEW-TEMPLATE-HERE.php')
Here, then, is the example from the WP Codex found in @Xeross’s link with the code snippet from the original question:
Kudos to @Xeross for providing the answer in a link and providing the documentation about where the template datum is stored. See @Xeross’s answer for more https://wordpress.stackexchange.com/a/24933/69247