WordPress – How to create a new page from the WordPress plugin

wordpress

In my wordpress plugin, I want to generate a page on the fly.

I could have the user create the page for me. But I would rather not have them do any steps. Just let them activate it and it works.

So I was wondering is there a way for me to do this, which maintains all the functionality within the plugin.

My initial idea was to add a rewrite rule

add_rewrite_rule('my_page/$', 'wp-content/plugins/my_plugin/page.php', 'top');

Then in my plugin I can have a page.php. Which works well, but I cannot get the header/footer etc.

I am very new to wordpress, so chances are i am missing somethign obvious.

Best Solution

You could create a 404 page code snippet that does wp_insert_post() and then redirects the user to it.

Your theme's 404.php would look like this:

<?php
$post_id = wp_insert_post("post_title" => "my post title", "post_content" => "Lol");
header("location:" . get_permalink( $post_id ) );
die();
?>
Related Question