Add html files as new pages

I am trying to add FTP uploaded html files (*.html) as new pages in WordPress and then extract the html content from the file and insert it into the editor of the created page.

So I am trying to write a function that will first:

  • Look for files of chosen directory (exclude files I don’t want).
  • Loop through each file and add just the name of the file (not the ext) as a new page entry in WordPress.
  • Take and extract all html data and put into the editor of the page.
    (Before adding as new page insert, if the page name already exists, update page data instead.)
  • Delete files once page is created.

So far I have this function I am working on:

    <?php

    function getHTMLFiles($dir,$exclude){ 

       $ffs = scandir($dir); //Scan my files in directory      

        foreach($ffs as $ff){ //loop through files

            if(is_array($exclude) and !in_array($ff,$exclude)){ 

              if($ff != '.' && $ff != '..'){ 

                if(!is_dir($dir.'/'.$ff)){

                   //Skip if there is a directory
                   echo ltrim($dir.'/'.$ff,'./'); //show files names

                } else { 

                   echo $ff;   //show my names

                   //Extract html File data
                   $htmlData = file_get_contents($ff);

                   //Attempt to find post id by post name if it exists
                   $post = get_page_by_path( $ff, OBJECT, 'page' ) ;
                   $pgid = $post->ID;

                    //Check If Page exist
                    if ( FALSE === get_post_status( $pgid ) ) { 


                      //Add new wp page into db               
                      wp_insert_post(array('post_title'=>$ff, 'post_type'=>'page', 'post_content'=>$htmlData));                         


                    } else {         

                      // Update post 
                      $my_post = array(
                          'ID'           => $pgid,
                          'post_title'   => $ff,
                          'post_content' => $htmlData,
                      );

                      // Update the post into the database
                      wp_update_post( $my_post );

                    } 

                   unlink($ff); //delete file                         



                } 

                if(is_dir($dir.'/'.$ff)) getHTMLFiles($dir.'/'.$ff,$exclude); 

              } 
           } 
        } 

    } 

    getHTMLFiles('/uploaded_files/',array('index.html','exclude.html')); 

    ?>

If you can help me if everything looks good or put me in the right direction, that would be awesome!

Read more here: Add html files as new pages

Leave a Reply

Your email address will not be published. Required fields are marked *