是否有一种方法可以在wordpress中以编程方式导入wordpress页面


Is there a way to programmatically import wordpress pages within wordpress?

我想在我的wordpress插件中创建这个功能。假设我有一组永远不会改变的页面,我想将它们自动导入到我建立的每个wordpress站点,而不必手动转到第一个站点,导出包含页面的xml文件,然后将其导入到新站点。对此有什么想法吗?

谢谢

如果您知道如何遍历XML文件,并且您的XML文件可以在其他站点上访问,则可以遍历以下代码:-

// 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 );

您需要在安装插件时启动此代码。

    你可以通过默认的Wordpress导出工具导出你的页面。这将产生。xml (WXR)文件。
  1. 之后,您可以通过WP-CLI工具在每个站点导入页面,使用以下命令:

    $ wp import file-name.xml

WXR 代表WordPress eXtended RSS

您可以将页面存储在数组中,然后在插件激活时自动插入它们。我建议为每个页面存储一个meta_key,这也让你知道它已经被插入,这样你就不用每次激活和停用插件时都创建它们。你可以把它放在插件的主文件中。请确保用实际的页面名称替换编号的页面和段,并将"my_plugin"替换为插件的命名空间。

    <?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' );
   ?>