My problem is to show a list of products read from db tables. I know how to read them and I am able to produce the table, but only using a shortcode embedded in a page that I've created via WP.

I want the plugin itself create a page with my table inside, and that this page is made available to the WP users via a menu item (not the admin menu).

What is the right way?


You can create the page via wp_insert_post( $post, $wp_error );. The array $post contains the data for your page, with the full documentation here.

Be sure to receive the ID from your inserted page/post. You can Add the page at the activation of your plugin, but please check first if the option for the page is already set (maybe from a previous install), because you can skip the creation of the page in this case:

function your_plugin_activate() {

    if ( !get_option( 'your_plugin_page_id' ) ) { // check if the option is already set

        $post = array(); //insert your postdata into this array
        $mypageid = wp_insert_post( $post ); // create the page/post
        update_option( 'your_plugin_page_id', $mypageid ); // set the option in the database for future reference

register_activation_hook( __FILE__, 'your_plugin_activate' );

This goes into your plugin file.

You can save this ID in your Plugin options, and use it to automatically filter the content and insert your table. Of course, you can also just insert the shortcode you are using directly into the post_content, but using

add_filter( 'the_content', 'your_table_function_name' );

function your_table_function_name( $content ) {

    if ( $GLOBALS['post']->ID == get_option( 'your_plugin_page_id' ) ) { // check if you are on the right page
        $content = $your_table_code . $content; // Set the Table in front of the User Content
    return $content; // return the content, any other page returns the original content.


gives you the advantage of being independent to the user input, as a faulty shortcode could prevent the table from being shown.

Please keep in mind that it would be very good for the user if you gave him the choice of choosing an existing page that should be filtered, or automatically creating a new one, as well as presenting an option for changing this page. If you saved the ID of your new page, this should not be too much effort :)

  • Many many thanks! Should I add this wp_insert_post() via a add_action('init', <func>) ? or maybe better during the plugin install? In this last case, how?
    – picus
    Jan 22 '14 at 10:01
  • I updated my answer to include the hook at installation, as well as the filter function :)
    – fischi
    Jan 22 '14 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.