0

sorry for my bad English.

I want to create multiple pages when activating a plugin. This also works, but how do I get different content in the different pages?

if (!current_user_can('activate_plugins')) return;

        $page_titles = array(
            'Login',
            'Dashboard'
        );

        foreach($page_titles as $page_title) {

            $page = get_page_by_title( $page_title );

            if( ! isset ( $page ) ) {

                // create post object
                $my_post = array(
                    'post_title'    =>  $page_title,
                    'post_content'  =>  '[shortcode]',
                    'post_status'   =>  'publish',
                    'post_author'   =>  get_current_user_id(),
                    'post_type'     =>  'page',
                );

                // insert the post into the database
                wp_insert_post($my_post);

            }
        }

I would be very happy to receive help

1
  • You would need to define that content somewhere, likely by replacing $page_titles with an array of arrays, e.g. $posts = [ [ 'title' => 'Login', 'content' => '[shortcode]' ], [ 'title' => 'Dashboard', ....
    – Tom J Nowell
    Commented Mar 16, 2021 at 10:49

1 Answer 1

1

You just add the content to your initial array. The most simple way is using the titles as array indices like this:

$pages = [
    'Login'     => 'Some content',
    'Dashboard' => 'Some other content'
];

foreach ( $pages as $title => $content ) 
{       
    if ( get_page_by_title( $title ) ) {
        continue; // skip this page
    }
    
    wp_insert_post([
        'post_title'    =>  $title,
        'post_content'  =>  $content,
        'post_status'   =>  'publish',
        'post_author'   =>  get_current_user_id(),
        'post_type'     =>  'page',
   ]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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