有没有办法以编程方式在wordpress中导入wordpress页面?

I'm trying to create this functionality within my wordpress plugin. Let's say I have a set number of pages that will never change and I want to automatically import them to every wordpress site I set up without having to manually go to the first site, export the xml file containing the pages then import it to the new site. Any thoughts on this?

Thanks

If you know how to loop through your XML file and your XML file is accessible on the other site you could loop through the following code:-

// Create post object
$my_post = array(
  'post_title'    => wp_strip_all_tags( $post_title ),
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => $cat
);

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

You would need to initiate this code on the install of your plugin.

  1. You can export your pages via default Wordpress export tool. That will result in .xml (WXR) file.
  2. After that you can import the pages via WP-CLI tool on each one site, with the following command:

    $ wp import file-name.xml

WXR stands for WordPress eXtended RSS.

You can store the pages in an array and then automatically insert them when your plugin is activated. I'd recommend storing a meta_key for each page that also let's you know it's already been inserted so that you don't create them every time the plugin is activated and deactivated. You can put this in the main file of your plugin. Be sure to replace the numbered pages and slugs with actual page names and to replace "my_plugin" with your plugin's namespace.

    <?php
    function create_my_plugin_pages() {
      $pages = array(
        'Page 1' => 'page-1', // Use slugs to create meta-keys
        'Page 2' => 'page-2',
        'Page 3' => 'page-3'
      );

      foreach( $pages as $title => $slug ) {
        $meta_key = 'my-plugin_'.$slug;

        // Check that the page wasn't already created
        $existing = get_posts(array(
          'post_type' => 'page',
          'meta_query' => array(
            array(
              'key' => $meta_key,
              'value' => '1'
            )
          )
        ));

        // Create page if it doesn't exist
        if ( !count($existing) ) {
          $new_page = wp_insert_post(array(
            'post_title' => $title,
            'post_status' => 'publish'
          ));

          add_post_meta($new_page,$meta_key,'1');
        }
      }
    }

    register_activation_hook( __FILE__, 'create_my_plugin_pages' );
   ?>