I’m trying to build a theme which would require specific pages to be included. Is there a way to automatically create pages and assign them to their page templates when a theme is installed?
Leave a Reply
You must be logged in to post a comment.
I’m trying to build a theme which would require specific pages to be included. Is there a way to automatically create pages and assign them to their page templates when a theme is installed?
You must be logged in to post a comment.
I got similiar situation where I needed to add page on theme activation and set it as homepage automatically.
Here’s how I did it:
Hope this helps someone.
Update:
Thanks Maruti Mohanty.
The previous link is broken. 🙁
The standard way is via
wp_insert_post
. You get a bunch of information on WP Codex: http://codex.wordpress.org/Function_Reference/wp_insert_postThis is bad practice. Themes are for presentation, they are visual, they shouldn’t be dictating actual content. If they do, then you’re doing it wrong and your code would be better off as a plugin.
However, should your theme have an ‘intended’ content arrangement, you should not auto-create the pages/content, you should not meddle with the users content at all, you could be breaking other things.
Instead, allow the user to select which pages should be used, in the same way settings allows you to pick a static page instead of latest posts, and how plugins like Woocommerce or Jigoshop let you choose which page is the checkout page etc ( those are plugins, it’s okay for them to create pages that way ).
Eitherway this indicates a fundamental flaw in your approach to building your theme ( or you’re building something for a client, and have decided to make it easy for them to install, creating more work for you, whereas you would be better off offering to install it yourself for a fee, which would be more profitable ).
Should you be foolish enough to actually attempt it anyway…
Refer to http://codex.wordpress.org/Function_Reference/wp_insert_post
But, you will need to check each ‘init’ to see if the pages exist. If they don’t create them, and update an option somewhere so that you remember they’ve been created and not to check the next time around, else you’ll end up with more pages created on every page load.
Using the code in this answer and a
wp_insert_post
I found in this theme.